diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a5dbd11..c0d076d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/changelog.d/2899-spans-weekly-wiki.md b/changelog.d/2899-spans-weekly-wiki.md new file mode 100644 index 00000000..dff60292 --- /dev/null +++ b/changelog.d/2899-spans-weekly-wiki.md @@ -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 (`/spans-view/data//.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 `` 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-.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`. diff --git a/docs/bridge-ops.md b/docs/bridge-ops.md index f9c1e05c..17168253 100644 --- a/docs/bridge-ops.md +++ b/docs/bridge-ops.md @@ -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//.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 ``; 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-.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 diff --git a/scripts/install-spans-weekly-timer.sh b/scripts/install-spans-weekly-timer.sh new file mode 100755 index 00000000..d9fa063b --- /dev/null +++ b/scripts/install-spans-weekly-timer.sh @@ -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/.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 < 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 <&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" diff --git a/scripts/install-spans-weekly-timer.test.sh b/scripts/install-spans-weekly-timer.test.sh new file mode 100755 index 00000000..c0b71029 --- /dev/null +++ b/scripts/install-spans-weekly-timer.test.sh @@ -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 ] diff --git a/scripts/spans-rollup.py b/scripts/spans-rollup.py index f388c4ee..a7230204 100755 --- a/scripts/spans-rollup.py +++ b/scripts/spans-rollup.py @@ -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. diff --git a/scripts/spans-weekly.py b/scripts/spans-weekly.py new file mode 100755 index 00000000..7813e711 --- /dev/null +++ b/scripts/spans-weekly.py @@ -0,0 +1,729 @@ +#!/usr/bin/env python3 +"""Weekly fleet span summary -> one Family Wiki page (#2899). + +The hub already keeps one checked, body-free record per node and KST day +(``spans-view-collect.sh`` -> ``spans-view.py build`` -> +``/spans-view/data/YYYY-MM-DD/.json`` plus ``_status.json``). +Once a week (Monday, after the 04:30 daily collection) this script folds the +previous Monday-Sunday of those records into one Markdown section and adds it +to a Wiki page through the normal PR-first path (``wiki-agent write-path`` -> +edit -> ``wiki-agent pr``). It opens no connection to any node. + + spans-weekly.py [--week YYYY-Www] [--nodes "a b c"] [--dry-run] [--page P] ... + +What a section holds (numbers and identifier-shaped names only): + +- per node: days collected (n/7), turns, tool calls, tool error rate, cost + (USD), the largest daily cost-ledger difference, a2a ok/failed when any + node reported a2a spans; one fleet total row; +- the five tools with the most errors (fleet-wide): calls, errors, rate, the + largest daily p95; +- "big changes" against the week before: the tool error rate rose by + ``--error-rate-pp`` points or more, or turns per collected day moved to + ``--turns-low`` x or below / ``--turns-high`` x or above (provisional + thresholds, also settable through ``CCC_SPANS_WEEKLY_*``); +- days not collected per node, with the reason codes the collector recorded. + +A week with no collected day at all gets a single 「수집 없음」 line. + +Page rules: + +- every section starts with ```` on its own + line; a week that already has that marker on the page or in its yearly + archive is never written again; +- the page keeps the newest 12 weeks, newest first; older sections move to + ``-archive-.md``; +- the top of the page holds one ``에이전트 다이제스트`` line for the newest + week so ``wiki-agent prefetch`` / ``find`` pick it up; +- the page's ``[DOC-N]`` id is allocated from the worktree when the page is + first created (the same rule as the work board, #2914). + +``--dry-run`` prints the target week's Markdown and nothing else: no Wiki +worktree is opened and no PR is made. ``--catch-up N`` (default 1) also adds +up to N earlier weeks still missing from the page, so a week whose PR failed +is retried on the next run. ``CCC_SPANS_VIEW_NOW`` (ISO timestamp) replaces +the clock; it is a test seam shared with spans-view.py. + +Exit 0 on success (including "nothing to add"), 2 on a usage or input error, +1 when the Wiki step failed. +""" +from __future__ import annotations + +import argparse +import fcntl +import importlib.util +import json +import os +import re +import subprocess +import sys +import tempfile +from collections import Counter +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Any, Optional, Sequence + +HERE = Path(__file__).resolve().parent +_SPEC = importlib.util.spec_from_file_location("ccc_spans_view", HERE / "spans-view.py") +assert _SPEC is not None and _SPEC.loader is not None +view = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(view) + +KST = view.KST +DEFAULT_PAGE = "pages/services/span-rollup.md" +KEEP_WEEKS = 12 +LOOKBACK_WEEKS = 11 # the hub keeps 90 days of records: 12 weeks back from the latest +MAX_CATCH_UP = 11 +MAX_NODES = 40 +TOP_TOOLS = 5 +MAX_NAME = 60 +MAX_SECTION_BYTES = 24 * 1024 +DEFAULT_ERROR_PP = 2.0 +DEFAULT_TURNS_LOW = 0.5 +DEFAULT_TURNS_HIGH = 2.0 + +_WEEK = re.compile(r"^\d{4}-W\d{2}$") +_MARKER = re.compile(r"^$", re.M) +_NAME_UNSAFE = re.compile(r"[^A-Za-z0-9._:/@+-]") +_PAGE = re.compile(r"^pages/[A-Za-z0-9._/-]+\.md$") +DIGEST_LINE = "> **에이전트 다이제스트** — status: `active` · " + + +class WeeklyError(Exception): + """The Wiki step failed; exit 1.""" + + +class UsageError(ValueError): + """Bad arguments or input; exit 2.""" + + +def marker(week: str) -> str: + return f"" + + +# ---------------------------------------------------------------------- weeks + + +def week_id(monday: date) -> str: + return monday.strftime("%G-W%V") + + +def parse_week(text: str) -> date: + if not _WEEK.match(text or ""): + raise UsageError("bad --week (want YYYY-Www)") + try: + monday = datetime.strptime(text + "-1", "%G-W%V-%u").date() + except ValueError as exc: + raise UsageError("bad --week (want YYYY-Www)") from exc + if week_id(monday) != text: # W53 of a 52-week year rolls over + raise UsageError("bad --week (no such ISO week)") + return monday + + +def latest_week(now: datetime) -> date: + """Monday of the last complete Monday-Sunday week (KST).""" + today = now.astimezone(KST).date() + return today - timedelta(days=today.weekday() + 7) + + +def check_week(monday: date, now: datetime) -> date: + latest = latest_week(now) + if monday > latest: + raise UsageError("--week is not complete yet (KST)") + if monday < latest - timedelta(weeks=LOOKBACK_WEEKS): + raise UsageError("--week is older than the kept records") + return monday + + +def week_range(monday: date) -> str: + return f"{monday.isoformat()} ~ {(monday + timedelta(days=6)).isoformat()}" + + +# ----------------------------------------------------------------------- data + + +def _name(value: Any) -> str: + """An identifier-shaped tool name: no Markdown, no HTML, no pipe, bounded.""" + text = _NAME_UNSAFE.sub("?", str(value))[:MAX_NAME] + return text or "?" + + +def _fields(record: dict) -> dict: + """The numbers this summary needs from one checked record, re-checked. + + Raises ``view.Invalid`` (or TypeError/AttributeError) on a wrong shape. + """ + totals = record["totals"] + out = { + "turns": view._int(totals.get("turns")), + "calls": view._int(totals.get("tool_calls")), + "errors": view._int(totals.get("tool_errors")), + "cost": sum(float(view._num(model.get("cost_usd"))) for model in record.get("models") or []), + "tools": [], + "ledger": None, + "a2a": None, + } + for tool in record.get("tools") or []: + out["tools"].append({"name": _name(tool.get("name")), "calls": view._int(tool.get("calls")), + "errors": view._int(tool.get("errors")), + "p95": view._num(tool.get("p95_ms"), optional=True)}) + ledger = record.get("ledger") or {} + if ledger.get("available") is True: + if not isinstance(ledger.get("within_target"), bool): + raise view.Invalid("schema") + out["ledger"] = {"max": view._num(ledger.get("max_diff_pct"), optional=True), + "within": ledger["within_target"]} + a2a = record.get("a2a") + if a2a is not None: + out["a2a"] = {"ok": view._int(a2a.get("ok")), "failed": view._int(a2a.get("failed"))} + return out + + +def _empty_node() -> dict: + return {"days": 0, "turns": 0, "calls": 0, "errors": 0, "cost": 0.0, "tools": {}, + "ledger_days": 0, "ledger_max": None, "ledger_over": 0, + "a2a": None, "missing": Counter()} + + +def _add(node: dict, fields: dict) -> None: + node["days"] += 1 + for key in ("turns", "calls", "errors", "cost"): + node[key] += fields[key] + for tool in fields["tools"]: + slot = node["tools"].setdefault(tool["name"], {"calls": 0, "errors": 0, "p95": None}) + slot["calls"] += tool["calls"] + slot["errors"] += tool["errors"] + if tool["p95"] is not None: + slot["p95"] = tool["p95"] if slot["p95"] is None else max(slot["p95"], tool["p95"]) + ledger = fields["ledger"] + if ledger is not None: + node["ledger_days"] += 1 + node["ledger_over"] += 0 if ledger["within"] else 1 + if ledger["max"] is not None: + node["ledger_max"] = ledger["max"] if node["ledger_max"] is None else max(node["ledger_max"], ledger["max"]) + if fields["a2a"] is not None: + node["a2a"] = node["a2a"] or {"ok": 0, "failed": 0} + node["a2a"]["ok"] += fields["a2a"]["ok"] + node["a2a"]["failed"] += fields["a2a"]["failed"] + + +def week_nodes(data_dir: Path, monday: date) -> list[str]: + """Every node the hub's status files name for the week (when --nodes is not given).""" + seen: set[str] = set() + for offset in range(7): + seen.update(view.load_status(data_dir, (monday + timedelta(days=offset)).isoformat())) + return sorted(seen)[:MAX_NODES] + + +def load_week(data_dir: Path, monday: date, nodes: list[str]) -> dict[str, dict]: + """Per-node week totals from the hub's records; a day not collected is a reason code.""" + result = {node: _empty_node() for node in nodes} + for offset in range(7): + day = (monday + timedelta(days=offset)).isoformat() + ran = os.path.lexists(data_dir / day / "_status.json") + status = view.load_status(data_dir, day) if ran else {} + for node in nodes: + slot = status.get(node) + if not ran: + result[node]["missing"]["no-run"] += 1 + continue + if slot is None: + result[node]["missing"]["no-result"] += 1 + continue + if slot["state"] not in view.COLLECTED: + result[node]["missing"][slot["detail"] or _name(slot["state"])] += 1 + continue + record = view.load_record(data_dir, day, node) + try: + fields = _fields(record) if record is not None else None + except (view.Invalid, TypeError, AttributeError, KeyError, ValueError): + fields = None + if fields is None: + result[node]["missing"]["record-invalid"] += 1 + continue + _add(result[node], fields) + return result + + +# ------------------------------------------------------------------- render + + +def _n(value: int) -> str: + return f"{value:,}" + + +def _rate(errors: int, calls: int) -> Optional[float]: + return 100.0 * errors / calls if calls else None + + +def _pct(value: Optional[float]) -> str: + return "-" if value is None else f"{value:.1f}%" + + +def _usd(value: float) -> str: + return f"${value:,.2f}" + + +def _ledger_cell(node: dict) -> str: + if not node["ledger_days"]: + return "원장 없음" + text = "비교 불가" if node["ledger_max"] is None else f"{node['ledger_max']:.1f}%" + return text + (f" (초과 {node['ledger_over']}일)" if node["ledger_over"] else "") + + +def _a2a_cell(a2a: Optional[dict]) -> str: + return "-" if a2a is None else f"{a2a['ok']:,}/{a2a['failed']:,}" + + +def big_changes(nodes: list[str], cur: dict, prev: dict, pp: float, low: float, high: float) -> list[str]: + lines = [] + for node in nodes: + now, before = cur[node], prev.get(node) + if not now["days"] or not before or not before["days"]: + continue + notes = [] + rate_now, rate_before = _rate(now["errors"], now["calls"]), _rate(before["errors"], before["calls"]) + if rate_now is not None and rate_before is not None and rate_now - rate_before >= pp - 1e-9: + notes.append(f"도구 오류율 {_pct(rate_before)} → {_pct(rate_now)} (+{rate_now - rate_before:.1f}%p)") + avg_now, avg_before = now["turns"] / now["days"], before["turns"] / before["days"] + if avg_before > 0: + ratio = avg_now / avg_before + if ratio <= low + 1e-9 or ratio >= high - 1e-9: + notes.append(f"수집일 평균 턴 {avg_before:,.1f} → {avg_now:,.1f} ({ratio:.2f}배)") + if notes: + lines.append(f"- {node} — " + " · ".join(notes)) + return lines + + +def _reasons(missing: Counter) -> str: + return " · ".join(f"{code} {count}" for code, count in sorted(missing.items(), key=lambda kv: (-kv[1], kv[0]))) + + +def _node_table(nodes: list[str], cur: dict, totals: dict) -> list[str]: + with_a2a = any(cur[n]["a2a"] is not None for n in nodes) + columns = ["노드", "수집일", "턴", "도구 호출", "도구 오류율", "비용(USD)", "원장 차이 최대"] + if with_a2a: + columns.append("a2a 성공/실패") + out = ["### 노드별", "", "| " + " | ".join(columns) + " |", "|---|---|" + "---:|" * (len(columns) - 2)] + for node in nodes: + slot = cur[node] + if slot["days"]: + row = [node, f"{slot['days']}/7", _n(slot["turns"]), _n(slot["calls"]), + _pct(_rate(slot["errors"], slot["calls"])), _usd(slot["cost"]), _ledger_cell(slot)] + else: + row = [node, "0/7", "-", "-", "-", "-", "-"] + if with_a2a: + row.append(_a2a_cell(slot["a2a"]) if slot["days"] else "-") + out.append("| " + " | ".join(row) + " |") + total = ["**플릿 합계**", f"{totals['days']}/{7 * len(nodes)}", _n(totals["turns"]), _n(totals["calls"]), + _pct(_rate(totals["errors"], totals["calls"])), _usd(totals["cost"]), "-"] + if with_a2a: + seen = [cur[n]["a2a"] for n in nodes if cur[n]["days"] and cur[n]["a2a"] is not None] + total.append(_a2a_cell({"ok": sum(a["ok"] for a in seen), "failed": sum(a["failed"] for a in seen)})) + return out + ["| " + " | ".join(total) + " |", ""] + + +def _tool_table(nodes: list[str], cur: dict) -> list[str]: + tools: dict[str, dict] = {} + for node in nodes: + for name, slot in cur[node]["tools"].items(): + agg = tools.setdefault(name, {"calls": 0, "errors": 0, "p95": None}) + agg["calls"] += slot["calls"] + agg["errors"] += slot["errors"] + if slot["p95"] is not None: + agg["p95"] = slot["p95"] if agg["p95"] is None else max(agg["p95"], slot["p95"]) + failing = sorted(((name, slot) for name, slot in tools.items() if slot["errors"]), + key=lambda kv: (-kv[1]["errors"], -(_rate(kv[1]["errors"], kv[1]["calls"]) or 0), kv[0])) + out = [f"### 오류가 많은 도구 상위 {TOP_TOOLS} (플릿 합산)", ""] + if not failing: + return out + ["도구 오류 없음.", ""] + out += ["| 도구 | 호출 | 오류 | 오류율 | p95 ms (일별 최대) |", "|---|---:|---:|---:|---:|"] + for name, slot in failing[:TOP_TOOLS]: + p95 = "-" if slot["p95"] is None else f"{slot['p95']:,.0f}" + out.append(f"| `{name}` | {_n(slot['calls'])} | {_n(slot['errors'])} | " + f"{_pct(_rate(slot['errors'], slot['calls']))} | {p95} |") + return out + [""] + + +def render_section(monday: date, nodes: list[str], cur: dict, prev: dict, + pp: float = DEFAULT_ERROR_PP, low: float = DEFAULT_TURNS_LOW, + high: float = DEFAULT_TURNS_HIGH) -> str: + week = week_id(monday) + out = [marker(week), f"## {week} · {week_range(monday)} (KST)", ""] + collected = [node for node in nodes if cur[node]["days"]] + totals = {key: sum(cur[n][key] for n in collected) for key in ("days", "turns", "calls", "errors", "cost")} + if not totals["days"]: + reasons: Counter = Counter() + for node in nodes: + reasons.update(cur[node]["missing"]) + why = _reasons(reasons) + out.append(f"- 수집 없음 — 이 주에는 수집된 날이 없습니다 (노드 {len(nodes)}" + + (f" · {why}" if why else "") + ").") + return "\n".join(out) + "\n" + + prev_week = week_id(monday - timedelta(weeks=1)) + prev_days = sum(slot["days"] for slot in prev.values()) + changes = big_changes(nodes, cur, prev, pp, low, high) if prev_days else [] + out += [f"- 요약: 수집 노드 {len(collected)}/{len(nodes)} · 수집일 {totals['days']}/{7 * len(nodes)} · " + f"턴 {_n(totals['turns'])} · 도구 호출 {_n(totals['calls'])} · " + f"도구 오류율 {_pct(_rate(totals['errors'], totals['calls']))} · " + f"비용 {_usd(totals['cost'])} · 큰 변화 {len(changes)}건", ""] + out += _node_table(nodes, cur, totals) + out += _tool_table(collected, cur) + out += ["### 전주 대비 큰 변화", "", + f"기준(잠정): 도구 오류율 +{pp:g}%p 이상, 또는 수집일 평균 턴 {low:g}배 이하·{high:g}배 이상. " + f"비교 대상 {prev_week}.", ""] + if not prev_days: + out.append(f"전주({prev_week}) 수집 기록이 없어 비교하지 않았습니다.") + else: + out += changes or ["없음."] + out += ["", "### 미수집", ""] + gaps = [f"- {node} — {sum(cur[node]['missing'].values())}일: {_reasons(cur[node]['missing'])}" + for node in nodes if cur[node]["missing"]] + out += gaps or ["없음 — 모든 노드를 7일 모두 수집했습니다."] + text = "\n".join(out) + "\n" + if len(text.encode("utf-8")) > MAX_SECTION_BYTES: + raise UsageError("week section is larger than the size cap") + return text + + +def build_section(data_dir: Path, monday: date, nodes: Optional[list[str]], pp: float, + low: float, high: float) -> str: + names = nodes if nodes else week_nodes(data_dir, monday) + cur = load_week(data_dir, monday, names) + prev = load_week(data_dir, monday - timedelta(weeks=1), names) + return render_section(monday, names, cur, prev, pp, low, high) + + +# --------------------------------------------------------------------- pages + + +def split_page(text: str) -> tuple[str, list[tuple[str, str]]]: + """``(head, [(week, section text), ...])``; a repeated week keeps its first copy.""" + found = list(_MARKER.finditer(text)) + head = text[: found[0].start()] if found else text + sections: list[tuple[str, str]] = [] + seen: set[str] = set() + for index, match in enumerate(found): + end = found[index + 1].start() if index + 1 < len(found) else len(text) + if match.group(1) in seen: + continue + seen.add(match.group(1)) + sections.append((match.group(1), text[match.start(): end].rstrip("\n") + "\n")) + return head, sections + + +def weeks_on(text: str) -> set[str]: + return set(_MARKER.findall(text)) + + +def archive_path(page: str, year: str) -> str: + return f"{page[:-3]}-archive-{year}.md" + + +def _doc_id(head: str) -> Optional[str]: + match = re.match(r"^# \[(DOC-\d+)\]", head) + return match.group(1) if match else None + + +def next_doc_number(pages: Path) -> int: + """One past the largest DOC/TM/ND number in the worktree (the work-board rule).""" + best = 0 + pattern = re.compile(r"\[(?:DOC|TM|ND)-(\d+)\]") + for path in pages.rglob("*.md"): + try: + for match in pattern.finditer(path.read_text(encoding="utf-8", errors="replace")): + best = max(best, int(match.group(1))) + except OSError: + continue + return best + 1 + + +def digest(section: str) -> str: + lines = section.splitlines() + heading = lines[1][3:] if len(lines) > 1 and lines[1].startswith("## ") else "?" + body = next((line[2:] for line in lines[2:] if line.startswith("- ")), "") + body = body[len("요약: "):] if body.startswith("요약: ") else body + return f"{DIGEST_LINE}최신 주 {heading} — {body}" + + +def page_head(doc_id: str, page: str, newest: str) -> str: + return "\n".join([ + f"# [{doc_id}] 스팬 주간 플릿 요약 (자동 생성)", + "", + digest(newest), + "> - 이 페이지: 허브가 매일 모으는 노드별 스팬 일일 집계를 주 1회(월요일) 묶은 플릿 요약이다. " + f"최근 {KEEP_WEEKS}주를 최신순으로 두고, 더 오래된 주는 연도별 보관 페이지 " + f"`{archive_path(page, 'YYYY')}`로 옮긴다. **손으로 고치지 말 것** — 주마다 생성기가 절을 더한다.", + "> - 근거: 허브의 spans-view 수집 기록(`spans-view/data/<날짜>/<노드>.json`, `_status.json`). " + "숫자와 도구 이름만 싣고 대화 본문·프롬프트·도구 입력은 싣지 않는다. " + "생성기: ccc-node `scripts/spans-weekly.py`(ccc-node#2899).", + "> - 읽는 법: 수집일은 n/7, 도구 오류율은 그 주 도구 호출 대비 오류, 원장 차이는 하루 단위 " + "비용 원장 교차검증의 최대값이다. 「큰 변화」 기준은 잠정값이다.", + "", + "", + ]) + + +def archive_head(doc_id: str, year: str, page: str) -> str: + return "\n".join([ + f"# [{doc_id}] 스팬 주간 플릿 요약 — {year} 보관 (자동 생성)", + "", + f"> - `{page}`에서 {KEEP_WEEKS}주가 지나 옮겨 온 {year}년(ISO 주 기준) 주간 절. 최신순. " + "**손으로 고치지 말 것.**", + "", + "", + ]) + + +def _join(head: str, sections: list[tuple[str, str]]) -> str: + return head + "\n".join(text for _, text in sections) + + +def merge_pages(page: str, read, add: dict[str, str], next_number: int) -> dict[str, str]: + """New text for every page that changes. ``read(path)`` returns the current text or ''.""" + old = read(page) + head, sections = split_page(old) + archives: dict[str, str] = {} + + def archived(year: str) -> str: + path = archive_path(page, year) + if path not in archives: + archives[path] = read(path) + return archives[path] + + if old and _doc_id(old) is None: + raise WeeklyError("the page exists but was not made by this generator; nothing changed") + fresh = {week: text for week, text in add.items() + if week not in {w for w, _ in sections} and week not in weeks_on(archived(week[:4]))} + if not fresh: + return {} + sections = sorted(sections + list(fresh.items()), key=lambda kv: kv[0], reverse=True) + keep, moved = sections[:KEEP_WEEKS], sections[KEEP_WEEKS:] + changes: dict[str, str] = {} + number = next_number + + doc_id = _doc_id(old) + if doc_id is None: + doc_id, number = f"DOC-{number}", number + 1 + changes[page] = page_head(doc_id, page, keep[0][1]) + "\n".join(text for _, text in keep) + + by_year: dict[str, list[tuple[str, str]]] = {} + for week, text in moved: + by_year.setdefault(week[:4], []).append((week, text)) + for year in sorted(by_year): + path = archive_path(page, year) + old_archive = archived(year) + if old_archive and _doc_id(old_archive) is None: + raise WeeklyError("an archive page exists but was not made by this generator; nothing changed") + a_head, a_sections = split_page(old_archive) + present = {w for w, _ in a_sections} + merged = sorted(a_sections + [kv for kv in by_year[year] if kv[0] not in present], + key=lambda kv: kv[0], reverse=True) + a_id = _doc_id(old_archive) + if a_id is None: + a_id, number = f"DOC-{number}", number + 1 + a_head = archive_head(a_id, year, page) + changes[path] = _join(a_head, merged) + return changes + + +# ------------------------------------------------------------------- publish + + +def _run(args: Sequence[str], cwd: Optional[Path] = None, timeout: int = 300) -> subprocess.CompletedProcess: + try: + return subprocess.run(list(args), cwd=cwd, capture_output=True, text=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + raise WeeklyError(f"{Path(args[0]).name} failed: {type(exc).__name__}") from None + + +def _porcelain(worktree: Path) -> list[str]: + res = _run(["git", "-C", str(worktree), "-c", "core.quotePath=false", "status", + "--porcelain=v1", "-z", "--untracked-files=all"]) + if res.returncode != 0: + raise WeeklyError(f"git status failed rc={res.returncode}") + return [entry[3:] for entry in res.stdout.split("\0") if entry] + + +def _inside(worktree: Path, rel: str) -> Path: + target = worktree / rel + root = os.path.realpath(worktree) + if target.is_symlink() or not os.path.realpath(target).startswith(root + os.sep): + raise WeeklyError("target page is a symlink or leaves the worktree") + return target + + +def _write(target: Path, text: str) -> None: + target.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=str(target.parent), prefix=".span-weekly.") + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + os.chmod(tmp, 0o644) + os.replace(tmp, target) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def publish(weeks: list[date], render, page: str = DEFAULT_PAGE, + wiki_agent_bin: str = "wiki-agent") -> dict: + """Add the weeks missing from the page (``render(monday)`` -> section) through a Wiki PR.""" + if not _PAGE.match(page) or ".." in page: + raise UsageError("--page must be a plain path under pages/") + res = _run([wiki_agent_bin, "write-path"]) + if res.returncode != 0: + raise WeeklyError(f"wiki-agent write-path failed rc={res.returncode}") + lines = [line.strip() for line in res.stdout.splitlines() if line.strip()] + if not lines: + raise WeeklyError("wiki-agent write-path printed no path") + worktree = Path(lines[-1]) + if not (worktree / "pages").is_dir(): + raise WeeklyError("wiki worktree has no pages/") + if _porcelain(worktree): + raise WeeklyError("wiki worktree is not clean before the weekly summary") + + def read(rel: str) -> str: + target = _inside(worktree, rel) + return target.read_text(encoding="utf-8") if target.exists() else "" + + main_text = read(page) + wanted = [w for w in weeks + if week_id(w) not in weeks_on(main_text) + and week_id(w) not in weeks_on(read(archive_path(page, week_id(w)[:4])))] + names = [week_id(w) for w in weeks] + if not wanted: + return {"ok": True, "changed": False, "page": page, "weeks": [], "present": names} + add = {week_id(w): render(w) for w in wanted} + changes = merge_pages(page, read, add, next_doc_number(worktree / "pages")) + if not changes: + return {"ok": True, "changed": False, "page": page, "weeks": [], "present": names} + for rel, text in changes.items(): + _write(_inside(worktree, rel), text) + unexpected = [path for path in _porcelain(worktree) if path not in changes] + if unexpected: + raise WeeklyError(f"unexpected paths changed: {unexpected[:3]}") + res = _run([wiki_agent_bin, "pr"], cwd=worktree, timeout=900) + if res.returncode != 0: + raise WeeklyError(f"wiki-agent pr failed rc={res.returncode}") + archived = sorted(path for path in changes if path != page) + return {"ok": True, "changed": True, "submitted": True, "page": page, + "weeks": sorted(add, reverse=True), "archives": archived} + + +# ----------------------------------------------------------------------- CLI + + +def _env_float(name: str, default: float) -> float: + text = os.environ.get(name, "") + try: + return float(text) if text else default + except ValueError: + raise UsageError(f"bad {name}") from None + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Weekly fleet span summary -> Family Wiki page (#2899).") + parser.add_argument("--week", help="ISO week YYYY-Www (default: the last complete week, KST)") + parser.add_argument("--nodes", help="space-separated node names (default: $CCC_FLEET_NODES, " + "else every node the week's status files name)") + parser.add_argument("--state-dir", default=os.environ.get("CCC_STATE_DIR") or str(Path.home() / ".claude" / "state")) + parser.add_argument("--data-dir", help="record folder (default: /spans-view/data)") + parser.add_argument("--page", default=os.environ.get("CCC_SPANS_WEEKLY_PAGE") or DEFAULT_PAGE) + parser.add_argument("--catch-up", type=int, default=1, + help=f"also add up to N earlier weeks missing from the page (0-{MAX_CATCH_UP})") + parser.add_argument("--error-rate-pp", type=float, default=None) + parser.add_argument("--turns-low", type=float, default=None) + parser.add_argument("--turns-high", type=float, default=None) + parser.add_argument("--wiki-agent-bin", default="wiki-agent") + parser.add_argument("--result-file", default="") + parser.add_argument("--dry-run", action="store_true", help="print the week's Markdown only") + return parser + + +def _thresholds(args: argparse.Namespace) -> tuple[float, float, float]: + pp = args.error_rate_pp if args.error_rate_pp is not None else _env_float("CCC_SPANS_WEEKLY_ERROR_PP", DEFAULT_ERROR_PP) + low = args.turns_low if args.turns_low is not None else _env_float("CCC_SPANS_WEEKLY_TURNS_LOW", DEFAULT_TURNS_LOW) + high = args.turns_high if args.turns_high is not None else _env_float("CCC_SPANS_WEEKLY_TURNS_HIGH", DEFAULT_TURNS_HIGH) + if not 0 < pp <= 100 or not 0 < low < 1 or not 1 < high <= 100: + raise UsageError("thresholds out of range (0 Path: + path = Path(args.data_dir) if args.data_dir else Path(args.state_dir) / "spans-view" / "data" + if path.is_symlink() or not path.is_dir(): + raise UsageError("no spans-view records folder (is the daily view installed on this node?)") + return path + + +def _nodes(args: argparse.Namespace) -> Optional[list[str]]: + text = args.nodes if args.nodes is not None else os.environ.get("CCC_FLEET_NODES", "") + if not text.strip(): + return None + try: + nodes = view.parse_nodes(text) + except view.UsageError as exc: + raise UsageError(str(exc)) from None + if len(nodes) > MAX_NODES: + raise UsageError(f"at most {MAX_NODES} nodes") + return nodes + + +def _summary(result: dict, target: str) -> str: + if result.get("changed"): + text = "스팬 주간 요약 PR 제출: " + ", ".join(result["weeks"]) + return text + (f" (보관 이동: {', '.join(result['archives'])})" if result.get("archives") else "") + return f"스팬 주간 요약 변경 없음: {target} 이미 있음" + + +def main(argv: Optional[Sequence[str]] = None) -> int: + args = build_parser().parse_args(argv) + lock = None + try: + now = view.clock() + pp, low, high = _thresholds(args) + monday = check_week(parse_week(args.week), now) if args.week else latest_week(now) + if not 0 <= args.catch_up <= MAX_CATCH_UP: + raise UsageError(f"--catch-up out of range (0-{MAX_CATCH_UP})") + data_dir = _data_dir(args) + nodes = _nodes(args) + + def render(week: date) -> str: + return build_section(data_dir, week, nodes, pp, low, high) + + if args.dry_run: + sys.stdout.write(render(monday)) + return 0 + oldest = latest_week(now) - timedelta(weeks=LOOKBACK_WEEKS) + weeks = [monday - timedelta(weeks=k) for k in range(args.catch_up, -1, -1)] + weeks = [w for w in weeks if w >= oldest] + state = Path(args.state_dir) + state.mkdir(parents=True, exist_ok=True) + lock = open(state / "spans-weekly.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + raise WeeklyError("another spans-weekly run holds the lock") from None + result = publish(weeks, render, args.page, args.wiki_agent_bin) + line = _summary(result, week_id(monday)) + if args.result_file: + Path(args.result_file).write_text(line + "\n", encoding="utf-8") + print(json.dumps({**result, "summary": line}, ensure_ascii=False)) + return 0 + except (UsageError, view.UsageError) as exc: + code, error = 2, str(exc) + except WeeklyError as exc: + code, error = 1, str(exc) + finally: + if lock is not None: + lock.close() + if args.result_file: + Path(args.result_file).write_text(f"스팬 주간 요약 실패: {error}\n", encoding="utf-8") + print(json.dumps({"ok": False, "error": error}, ensure_ascii=False)) + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/spans_weekly_test.py b/scripts/spans_weekly_test.py new file mode 100644 index 00000000..9f637d17 --- /dev/null +++ b/scripts/spans_weekly_test.py @@ -0,0 +1,485 @@ +"""Hermetic tests for scripts/spans-weekly.py (#2899). + +Every fixture is a synthetic hub record folder (``//.json`` + +``_status.json``, written through spans-view.py's own normalizer) and a fake +``wiki-agent`` over a temp git worktree, so the assertions are about the +weekly contract — the section shape, escaping, the marker gate, archiving, +the no-data week, thresholds, dry-run — never about this host's spans. +""" + +from __future__ import annotations + +import fcntl +import importlib.util +import json +import os +import subprocess +import sys +from datetime import date, timedelta +from pathlib import Path + +import pytest + +HERE = Path(__file__).resolve().parent +_SPEC = importlib.util.spec_from_file_location("spans_weekly", HERE / "spans-weekly.py") +assert _SPEC is not None and _SPEC.loader is not None +weekly = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(weekly) +view = weekly.view +SCRIPT = HERE / "spans-weekly.py" + +NOW = "2026-11-23T05:00:00+09:00" # Monday; the last complete week is 2026-W47 +W47 = date(2026, 11, 16) +W46 = date(2026, 11, 9) +NODES = ["node-a", "node-b", "node-c"] +BODY = "SECRET BODY TEXT please never copy me" + + +def summary(node, day, turns=10, calls=100, errors=1, cost=0.5, tools=None, a2a=None, ledger=None, empty=False): + data = { + "schema": "ccc.spans-rollup.v1", "date": day, "node": node, "empty": empty, + "totals": {"spans": turns + calls, "turns": turns, "tool_calls": calls, "tool_errors": errors, + "tool_error_rate_pct": round(100.0 * errors / calls, 2) if calls else 0.0}, + "tools": tools if tools is not None else { + "Bash": {"calls": calls, "errors": errors, "error_rate_pct": 0.0, "p50_ms": 10.0, "p95_ms": 500.0}}, + "models": {"model-a": {"turns": turns, "input_tokens": 1, "output_tokens": 1, "cost_usd": cost}}, + "cost_ledger_check": ledger if ledger is not None else { + "available": True, "within_target": True, "max_diff_pct": 1.0, "target_pct": 5.0}, + "prompt": BODY, # unknown key: dropped by the view's normalizer, never reaches the page + } + if a2a is not None: + data["a2a"] = a2a + return data + + +def put_day(data: Path, day: str, nodes: dict): + """``nodes``: name -> summary dict (collected) or (state, detail) (not collected).""" + folder = data / day + folder.mkdir(parents=True, exist_ok=True) + status = {} + for node, value in nodes.items(): + if isinstance(value, tuple): + status[node] = {"state": value[0], "detail": value[1]} + continue + record = view.normalize_summary(value, day) + (folder / f"{node}.json").write_text(json.dumps(record), encoding="utf-8") + status[node] = {"state": "empty" if record["empty"] else "ok", "detail": ""} + (folder / "_status.json").write_text(json.dumps({"schema": view.STATUS_SCHEMA, "date": day, + "nodes": status}), encoding="utf-8") + + +def put_week(data: Path, monday: date, make): + for offset in range(7): + day = (monday + timedelta(days=offset)).isoformat() + put_day(data, day, make(day, offset)) + + +@pytest.fixture +def data(tmp_path, monkeypatch): + monkeypatch.setenv("CCC_SPANS_VIEW_NOW", NOW) + for name in ("CCC_FLEET_NODES", "CCC_SPANS_WEEKLY_ERROR_PP", "CCC_SPANS_WEEKLY_TURNS_LOW", + "CCC_SPANS_WEEKLY_TURNS_HIGH", "CCC_SPANS_WEEKLY_PAGE"): + monkeypatch.delenv(name, raising=False) + folder = tmp_path / "state" / "spans-view" / "data" + folder.mkdir(parents=True) + return folder + + +def standard_fleet(data: Path): + """W46 and W47 for three nodes: node-a busy, node-b with gaps, node-c silent.""" + def w46(day, i): + return {"node-a": summary("node-a", day, turns=10, calls=100, errors=1), + "node-b": summary("node-b", day, turns=10, calls=100, errors=1), + "node-c": ("missing", "no-folder")} + + def w47(day, i): + nodes = {"node-a": summary("node-a", day, turns=10, calls=100, errors=3, + a2a={"spans": 3, "ok": 2, "failed": 1}), + "node-c": ("missing", "no-folder")} + if i < 4: + nodes["node-b"] = summary("node-b", day, turns=30, calls=100, errors=1) + elif i < 6: + nodes["node-b"] = ("unreachable", "ssh-255") + return nodes # Sunday: node-b absent from the status file (no-result) + put_week(data, W46, w46) + put_week(data, W47, w47) + + +def dry_run(data: Path, capsys, *extra) -> tuple[int, str]: + rc = weekly.main(["--dry-run", "--data-dir", str(data), *extra]) + return rc, capsys.readouterr().out + + +# ------------------------------------------------------------------ section + + +def test_dry_run_prints_the_previous_week_and_is_stable(data, capsys): + standard_fleet(data) + rc, out = dry_run(data, capsys, "--nodes", " ".join(NODES)) + assert rc == 0 + lines = out.splitlines() + assert lines[0] == "" + assert lines[1] == "## 2026-W47 · 2026-11-16 ~ 2026-11-22 (KST)" + assert lines[3] == ("- 요약: 수집 노드 2/3 · 수집일 11/21 · 턴 190 · 도구 호출 1,100 · 도구 오류율 2.3% · " + "비용 $5.50 · 큰 변화 2건") + assert "| 노드 | 수집일 | 턴 | 도구 호출 | 도구 오류율 | 비용(USD) | 원장 차이 최대 | a2a 성공/실패 |" in lines + assert "| node-a | 7/7 | 70 | 700 | 3.0% | $3.50 | 1.0% | 14/7 |" in lines + assert "| node-b | 4/7 | 120 | 400 | 1.0% | $2.00 | 1.0% | - |" in lines + assert "| node-c | 0/7 | - | - | - | - | - | - |" in lines + assert "| **플릿 합계** | 11/21 | 190 | 1,100 | 2.3% | $5.50 | - | 14/7 |" in lines + assert "| `Bash` | 1,100 | 25 | 2.3% | 500 |" in lines + assert "- node-a — 도구 오류율 1.0% → 3.0% (+2.0%p)" in lines + assert "- node-b — 수집일 평균 턴 10.0 → 30.0 (3.00배)" in lines + assert "- node-b — 3일: ssh-255 2 · no-result 1" in lines + assert "- node-c — 7일: no-folder 7" in lines + assert BODY not in out + rc2, again = dry_run(data, capsys, "--nodes", " ".join(NODES)) + assert rc2 == 0 and again == out + + +def test_dry_run_never_calls_wiki_agent(data, capsys, tmp_path): + standard_fleet(data) + calls = tmp_path / "calls" + agent = _exe(tmp_path / "wiki-agent", f"#!/usr/bin/env bash\necho \"$@\" >> {str(calls)!r}\n") + rc, out = dry_run(data, capsys, "--nodes", "node-a", "--wiki-agent-bin", str(agent)) + assert rc == 0 and out.startswith("": {"calls": 5, "errors": 5, "error_rate_pct": 100.0}, + "[link](http://example.invalid)": {"calls": 4, "errors": 2, "error_rate_pct": 50.0}, + "A" * 300: {"calls": 3, "errors": 1, "error_rate_pct": 33.3}} + put_week(data, W47, lambda day, i: {"node-a": summary("node-a", day, tools=evil)}) + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert out.count("", "## 2026-W47 · 2026-11-16 ~ 2026-11-22 (KST)", "", + "- 수집 없음 — 이 주에는 수집된 날이 없습니다 (노드 2 · no-folder 7 · ssh-255 7)."] + + +def test_hub_did_not_run_is_its_own_reason(data, capsys): + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "- 수집 없음 — 이 주에는 수집된 날이 없습니다 (노드 1 · no-run 7)." in out + + +def test_idle_days_count_as_collected(data, capsys): + put_week(data, W47, lambda day, i: {"node-a": summary("node-a", day, turns=0, calls=0, errors=0, cost=0.0, + tools={}, empty=True, + ledger={"available": False})}) + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "| node-a | 7/7 | 0 | 0 | - | $0.00 | 원장 없음 |" in out + assert "도구 오류 없음." in out and "없음 — 모든 노드를 7일 모두 수집했습니다." in out + + +def test_corrupt_record_is_a_gap_not_a_crash(data, capsys): + put_week(data, W47, lambda day, i: {"node-a": summary("node-a", day)}) + (data / "2026-11-18" / "node-a.json").write_text("{not json", encoding="utf-8") + bad = json.loads((data / "2026-11-19" / "node-a.json").read_text()) + bad["totals"]["turns"] = -5 + (data / "2026-11-19" / "node-a.json").write_text(json.dumps(bad), encoding="utf-8") + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "| node-a | 5/7 |" in out and "- node-a — 2일: record-invalid 2" in out + + +def test_ledger_over_target_days_are_counted(data, capsys): + def make(day, i): + ledger = {"available": True, "within_target": i != 2, "max_diff_pct": 9.5 if i == 2 else 1.0} + return {"node-a": summary("node-a", day, ledger=ledger)} + put_week(data, W47, make) + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "| node-a | 7/7 | 70 | 700 | 1.0% | $3.50 | 9.5% (초과 1일) |" in out + + +# --------------------------------------------------------------- thresholds + + +def _two_weeks(data, before, after): + put_week(data, W46, lambda day, i: {"node-a": summary("node-a", day, **before)}) + put_week(data, W47, lambda day, i: {"node-a": summary("node-a", day, **after)}) + + +@pytest.mark.parametrize("before,after,flagged", [ + ({"errors": 1}, {"errors": 3}, True), # +2.0pp exactly + ({"errors": 10}, {"errors": 11}, False), # +1.0pp + ({"errors": 3}, {"errors": 1}, False), # a drop is not a big change + ({"turns": 10}, {"turns": 5}, True), # 0.5x exactly + ({"turns": 10}, {"turns": 6}, False), + ({"turns": 10}, {"turns": 20}, True), # 2x exactly + ({"turns": 10}, {"turns": 19}, False), +]) +def test_default_thresholds(data, capsys, before, after, flagged): + _two_weeks(data, before, after) + _, out = dry_run(data, capsys, "--nodes", "node-a") + section = out.split("### 전주 대비 큰 변화")[1].split("### 미수집")[0] + assert ("- node-a — " in section) is flagged + assert ("큰 변화 1건" if flagged else "큰 변화 0건") in out + + +def test_thresholds_are_configurable_by_flag_and_env(data, capsys, monkeypatch): + _two_weeks(data, {"errors": 10, "turns": 10}, {"errors": 11, "turns": 14}) + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "큰 변화 0건" in out + _, out = dry_run(data, capsys, "--nodes", "node-a", "--error-rate-pp", "1", "--turns-high", "1.4") + assert "기준(잠정): 도구 오류율 +1%p 이상, 또는 수집일 평균 턴 0.5배 이하·1.4배 이상." in out + assert "(+1.0%p)" in out and "(1.40배)" in out + monkeypatch.setenv("CCC_SPANS_WEEKLY_ERROR_PP", "0.5") + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "+0.5%p 이상" in out and "큰 변화 1건" in out + + +@pytest.mark.parametrize("flags", [["--error-rate-pp", "0"], ["--turns-low", "1"], ["--turns-high", "1"], + ["--turns-high", "500"], ["--catch-up", "12"]]) +def test_out_of_range_settings_are_refused(data, capsys, flags): + rc, out = dry_run(data, capsys, "--nodes", "node-a", *flags) + assert rc == 2 and json.loads(out)["ok"] is False + + +def test_previous_week_without_records_is_not_compared(data, capsys): + put_week(data, W47, lambda day, i: {"node-a": summary("node-a", day)}) + _, out = dry_run(data, capsys, "--nodes", "node-a") + assert "전주(2026-W46) 수집 기록이 없어 비교하지 않았습니다." in out and "큰 변화 0건" in out + + +# ---------------------------------------------------------------------- weeks + + +def test_week_selection(data, capsys): + now = view.datetime.fromisoformat(NOW) + assert weekly.latest_week(now) == W47 + assert weekly.latest_week(view.datetime.fromisoformat("2026-11-29T23:00:00+09:00")) == W47 # Sunday + assert weekly.parse_week("2026-W47") == W47 + assert weekly.parse_week("2026-W53") == date(2026, 12, 28) # 2026 has 53 ISO weeks + for bad in ("2025-W53", "2026-47", "2026-W5", "W47"): + with pytest.raises(weekly.UsageError): + weekly.parse_week(bad) + for week, rc in (("2026-W48", 2), ("2026-W35", 2), ("2026-W36", 0), ("2026-W46", 0)): + assert dry_run(data, capsys, "--nodes", "node-a", "--week", week)[0] == rc, week + + +def test_missing_records_folder_is_a_usage_error(tmp_path, capsys, monkeypatch): + monkeypatch.setenv("CCC_SPANS_VIEW_NOW", NOW) + rc = weekly.main(["--dry-run", "--state-dir", str(tmp_path / "nowhere")]) + assert rc == 2 and "records folder" in capsys.readouterr().out + + +def test_bad_node_names_are_refused(data, capsys): + rc, out = dry_run(data, capsys, "--nodes", "node-a ../x") + assert rc == 2 + + +# ---------------------------------------------------------------- page merge + + +def section(week: str) -> str: + return f"{weekly.marker(week)}\n## {week} · x (KST)\n\n- 요약: 주 {week}\n" + + +def test_merge_creates_page_with_digest_and_doc_id(): + pages: dict[str, str] = {} + changes = weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), + {"2026-W47": section("2026-W47")}, 121) + text = changes[weekly.DEFAULT_PAGE] + lines = text.splitlines() + assert lines[0] == "# [DOC-121] 스팬 주간 플릿 요약 (자동 생성)" + assert lines[2] == "> **에이전트 다이제스트** — status: `active` · 최신 주 2026-W47 · x (KST) — 주 2026-W47" + assert text.count("") == 1 and list(changes) == [weekly.DEFAULT_PAGE] + + +def test_merge_is_a_no_op_for_a_week_already_present(): + pages = weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: "", {"2026-W47": section("2026-W47")}, 5) + again = weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), + {"2026-W47": section("2026-W47") + "changed numbers\n"}, 6) + assert again == {} + + +def test_merge_keeps_twelve_weeks_newest_first_and_archives_the_rest(): + weeks = [weekly.week_id(date(2026, 1, 5) + timedelta(weeks=k)) for k in range(12)] # 2026-W02..W13 + pages: dict[str, str] = {} + for week in weeks: + pages.update(weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), {week: section(week)}, 40)) + main = pages[weekly.DEFAULT_PAGE] + assert weekly.weeks_on(main) == set(weeks) and len(pages) == 1 + order = [w for w, _ in weekly.split_page(main)[1]] + assert order == sorted(weeks, reverse=True) + pages.update(weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), + {"2026-W14": section("2026-W14")}, 41)) + archive = "pages/services/span-rollup-archive-2026.md" + main = pages[weekly.DEFAULT_PAGE] + assert "2026-W02" not in weekly.weeks_on(main) and "2026-W14" in weekly.weeks_on(main) + assert len(weekly.weeks_on(main)) == 12 and main.startswith("# [DOC-40]") + assert "최신 주 2026-W14" in main.splitlines()[2] + assert pages[archive].startswith("# [DOC-41] 스팬 주간 플릿 요약 — 2026 보관") + assert weekly.weeks_on(pages[archive]) == {"2026-W02"} + # an archived week is not written back onto the page + assert weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), + {"2026-W02": section("2026-W02")}, 42) == {} + # the next move keeps the archive's id and newest-first order + pages.update(weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), + {"2026-W15": section("2026-W15")}, 42)) + assert pages[archive].startswith("# [DOC-41]") + assert [w for w, _ in weekly.split_page(pages[archive])[1]] == ["2026-W03", "2026-W02"] + + +def test_archive_goes_by_iso_year(): + pages: dict[str, str] = {} + start = date(2025, 10, 20) # 2025-W43 .. 2026-W03 crosses the year + for k in range(13): + week = weekly.week_id(start + timedelta(weeks=k)) + pages.update(weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: pages.get(p, ""), {week: section(week)}, 7)) + assert weekly.weeks_on(pages["pages/services/span-rollup-archive-2025.md"]) == {"2025-W43"} + + +def test_merge_refuses_a_hand_made_page(): + with pytest.raises(weekly.WeeklyError, match="not made by this generator"): + weekly.merge_pages(weekly.DEFAULT_PAGE, lambda p: "# Something else\n", {"2026-W47": section("2026-W47")}, 1) + + +# ------------------------------------------------------------------- publish + + +def _exe(path: Path, text: str) -> Path: + path.write_text(text, encoding="utf-8") + path.chmod(0o755) + return path + + +def fake_wiki(tmp: Path) -> tuple[Path, Path, Path]: + wt = tmp / "wiki" + (wt / "pages" / "nodes").mkdir(parents=True) + (wt / "pages" / "nodes" / "a.md").write_text("# [DOC-41] A\n\n## [ND-120] fact\n", encoding="utf-8") + git = ["git", "-C", str(wt), "-c", "user.email=t@t", "-c", "user.name=t"] + subprocess.run(["git", "init", "-q", str(wt)], check=True) + subprocess.run([*git, "add", "-A"], check=True) + subprocess.run([*git, "commit", "-qm", "base"], check=True) + calls = tmp / "pr-calls" + agent = _exe(tmp / "wiki-agent", f"""#!/usr/bin/env bash +case "$1" in + write-path) echo "log line" >&2; echo {str(wt)!r} ;; + pr) echo "pr $(pwd)" >> {str(calls)!r}; git -c user.email=t@t -c user.name=t add -A && \\ + git -c user.email=t@t -c user.name=t commit -qm weekly ;; + *) exit 9 ;; +esac +""") + return wt, agent, calls + + +def run_cli(data: Path, agent: Path, tmp: Path, *extra) -> tuple[int, dict, str]: + result = tmp / "result.txt" + cmd = [sys.executable, str(SCRIPT), "--data-dir", str(data), "--state-dir", str(tmp / "state"), + "--wiki-agent-bin", str(agent), "--result-file", str(result), "--nodes", " ".join(NODES), *extra] + env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "CCC_SPANS_VIEW_NOW": NOW} + out = subprocess.run(cmd, capture_output=True, text=True, env=env) + line = result.read_text(encoding="utf-8") if result.exists() else "" + return out.returncode, json.loads(out.stdout.strip().splitlines()[-1]), line + + +def test_publish_adds_week_and_catch_up_then_skips(data, tmp_path): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + rc, res, line = run_cli(data, agent, tmp_path) + assert rc == 0 and res["changed"] and res["weeks"] == ["2026-W47", "2026-W46"] + assert line == "스팬 주간 요약 PR 제출: 2026-W47, 2026-W46\n" + page = (wt / weekly.DEFAULT_PAGE).read_text(encoding="utf-8") + assert page.startswith("# [DOC-121] 스팬 주간 플릿 요약 (자동 생성)") + assert "최신 주 2026-W47 · 2026-11-16 ~ 2026-11-22 (KST) — 수집 노드 2/3" in page.splitlines()[2] + assert page.index("span-weekly:2026-W47") < page.index("span-weekly:2026-W46") + assert oct((wt / weekly.DEFAULT_PAGE).stat().st_mode & 0o777) == "0o644" + assert calls.read_text().count("pr ") == 1 and BODY not in page + rc, res, line = run_cli(data, agent, tmp_path) + assert rc == 0 and res["changed"] is False and line == "스팬 주간 요약 변경 없음: 2026-W47 이미 있음\n" + assert calls.read_text().count("pr ") == 1 + assert (wt / weekly.DEFAULT_PAGE).read_text(encoding="utf-8").count("span-weekly:2026-W47") == 1 + + +def test_publish_without_catch_up_adds_only_the_target_week(data, tmp_path): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + rc, res, _ = run_cli(data, agent, tmp_path, "--catch-up", "0") + assert rc == 0 and res["weeks"] == ["2026-W47"] + + +def test_publish_refuses_dirty_worktree_and_symlinked_page(data, tmp_path): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + (wt / "pages" / "stray.md").write_text("x", encoding="utf-8") + rc, res, line = run_cli(data, agent, tmp_path) + assert rc == 1 and "not clean" in res["error"] and line.startswith("스팬 주간 요약 실패:") + (wt / "pages" / "stray.md").unlink() + (wt / "pages" / "services").mkdir() + (wt / "pages" / "services" / "span-rollup.md").symlink_to(tmp_path / "elsewhere.md") + subprocess.run(["git", "-C", str(wt), "-c", "user.email=t@t", "-c", "user.name=t", "add", "-A"], check=True) + subprocess.run(["git", "-C", str(wt), "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "l"], + check=True) + rc, res, _ = run_cli(data, agent, tmp_path) + assert rc == 1 and "symlink" in res["error"] and not (tmp_path / "elsewhere.md").exists() + assert not calls.exists() + + +def test_publish_refuses_a_bad_page_path(data, tmp_path): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + rc, res, _ = run_cli(data, agent, tmp_path, "--page", "../etc/x.md") + assert rc == 2 and not calls.exists() + + +def test_pr_failure_is_reported_and_retried_next_week(data, tmp_path, monkeypatch): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + broken = _exe(tmp_path / "wiki-agent-broken", f"""#!/usr/bin/env bash +case "$1" in + write-path) echo {str(wt)!r} ;; + pr) git -C {str(wt)!r} checkout -q -- . ; git -C {str(wt)!r} clean -qfd ; exit 4 ;; +esac +""") + rc, res, line = run_cli(data, broken, tmp_path, "--catch-up", "0") + assert rc == 1 and "wiki-agent pr failed rc=4" in res["error"] and "실패" in line + put_week(data, date(2026, 11, 23), lambda day, i: {"node-a": summary("node-a", day)}) + result = tmp_path / "r2" + cmd = [sys.executable, str(SCRIPT), "--data-dir", str(data), "--state-dir", str(tmp_path / "state"), + "--wiki-agent-bin", str(agent), "--result-file", str(result), "--nodes", "node-a"] + env = {**os.environ, "CCC_SPANS_VIEW_NOW": "2026-11-30T05:00:00+09:00"} + out = subprocess.run(cmd, capture_output=True, text=True, env=env) + assert out.returncode == 0, out.stdout + out.stderr + assert json.loads(out.stdout)["weeks"] == ["2026-W48", "2026-W47"] + + +def test_lock_blocks_a_second_run(data, tmp_path): + standard_fleet(data) + wt, agent, calls = fake_wiki(tmp_path) + (tmp_path / "state").mkdir(exist_ok=True) + with open(tmp_path / "state" / "spans-weekly.lock", "w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + rc, res, line = run_cli(data, agent, tmp_path) + assert rc == 1 and "holds the lock" in res["error"] and not calls.exists() + + +# ------------------------------------------------------------------ rollup + + +def test_rollup_candidate_points_at_the_services_page(): + text = (HERE / "spans-rollup.py").read_text(encoding="utf-8") + assert 'SUGGESTED_PATH = "pages/services/span-rollup.md"' in text + assert weekly.DEFAULT_PAGE == "pages/services/span-rollup.md"