Skip to content

martin1847/evolab / skills/cto-orchestration

cto-orchestration

Unverified

以 CTO/orchestrator 模式管理多 agent 软件交付。用户要求“你做 CTO/编排者”“派 omp/codex 去做”“goal 模式派发”、管理多会话开发或接入这套工作流时使用;“复盘/收口/retro/retrospective”“工作盘点/盘点候选/stocktake”也必须触发,盘点只提案不动工。新项目先用 repo-governance-bootstrap 建治理骨架。不用于单 agent 小任务、无需评审循环的局部改动或纯文档初始化。

FileKindSize
README.mdmarkdown5.3 KB
SKILL.mdskill md15.8 KB
references/agentctl/README.mdmarkdown26.8 KB
references/agentctl/agentctlexecutablescript57.6 KB
references/agentctl/codegraph-hooks.shexecutablescript2.5 KB
references/agentctl/cto-guard-agent.pyexecutablescript26.6 KB
references/agentctl/cto-guard-bash.pyexecutablescript150.5 KB
references/agentctl/cto-guard-edit.pyexecutablescript16.7 KB
references/agentctl/cto-guard-stop.pyexecutablescript7.6 KB
references/agentctl/duplexctl.pyexecutablescript239.5 KB
references/agentctl/guard-hooks.jsonconfig1.5 KB
references/agentctl/identity.pyexecutablescript113.5 KB
references/agentctl/post-checkout-codegraph.shscript18 B
references/agentctl/seat-census.pyscript10.8 KB
references/agentctl/watchctl.pyexecutablescript143.2 KB
references/agents-md-orchestration-section.mdmarkdown5.3 KB
references/decision-queue.mdmarkdown5.7 KB
references/dispatch-baseline.mdmarkdown3.7 KB
references/doc-lifecycle.pyexecutablescript9.2 KB
references/frontend-verify.mdmarkdown7.9 KB
references/goal-clauses.mdmarkdown8.0 KB
references/goal-preflight.pyexecutablescript40.9 KB
references/goal-template.mdmarkdown10.8 KB
references/implementation-discipline.mdmarkdown8.0 KB
references/measurement-protocol.mdmarkdown4.2 KB
references/onboarding-checklist.mdmarkdown3.2 KB
references/queue-freshness.pyexecutablescript3.8 KB
references/queue-hooks.jsonconfig617 B
references/retro-check.shexecutablescript28.2 KB
references/retro-hooks.jsonconfig2.2 KB
references/retro-reminder.shexecutablescript5.8 KB
references/retrospective.mdmarkdown7.7 KB
references/review-brief-preamble.mdmarkdown3.4 KB
references/review-dispatch.mdmarkdown14.4 KB
references/session-economics.pyexecutablescript18.2 KB
references/shock-in-the-loop.mdmarkdown3.8 KB
references/stocktake.mdmarkdown2.3 KB

references/retro-check.sh

View on GitHub
#!/usr/bin/env bash
# retro-check.sh — deterministic mechanical check for cto-orchestration 复盘 (SKILL.md §5).
# Verifies mechanical proxies only, not semantic quality. Independent invalid-state checks
# return non-zero; optional status files have no age or rewrite requirement.
#
# Usage:
#   bash retro-check.sh --base <branch> --docs <docs-dir> [--ledger <path>] [--memory <MEMORY.md>] [--memory-cap N] [--repo <git-dir>]
# Defaults: --base auto-detected (origin/HEAD → main/master/develop); --docs docs; --memory-cap 45.
set -uo pipefail

BASE=""; DOCS="docs"; MEMORY=""; MEMCAP=45; REPO="."
while [ $# -gt 0 ]; do case "$1" in
  --base) BASE="$2"; shift 2;;
  --docs) DOCS="$2"; shift 2;;
  --ledger)
    if [ $# -lt 2 ] || [ -z "$2" ] || [[ "$2" = --* ]]; then
      echo "--ledger requires a non-empty path" >&2; exit 2
    fi
    shift 2;; # compatibility only; no manual accounting requirement
  --memory) MEMORY="$2"; shift 2;;
  --memory-cap) MEMCAP="$2"; shift 2;;
  --repo) REPO="$2"; shift 2;;
  *) echo "unknown arg: $1"; exit 2;;
esac; done

TODAY="$(date +%F)"
# Advisory phases window: yesterday 00:00 local through now (or today if date arithmetic
# is unavailable). Status truth is not inferred from this window or document age.
YDAY="$(date -v-1d +%F 2>/dev/null || date -d 'yesterday' +%F 2>/dev/null)"
fails=0; warns=0
ok(){ echo "  [ok]   $*"; }
fail(){ echo "  [FAIL] $*"; fails=$((fails+1)); }
warn(){ echo "  [warn] $*"; warns=$((warns+1)); }

echo "== retro-check (date=$TODAY) =="

# resolve base branch
if [ -z "$BASE" ]; then
  BASE="$(git -C "$REPO" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')"
  [ -z "$BASE" ] && for b in main master develop; do git -C "$REPO" show-ref --verify --quiet "refs/remotes/origin/$b" && BASE="$b" && break; done
fi
[ -z "$BASE" ] && { warn "could not resolve base branch (pass --base); skipping worktree-merged check"; }

# 1) stray LINKED worktrees on already-merged branches (excludes the main checkout)
echo "1) worktree 核对 (已合分支无孤儿; 主 checkout 豁免):"
if [ -n "$BASE" ] && git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1; then
  if git -C "$REPO" fetch -q origin "$BASE" 2>/dev/null; then FETCH_OK=1; else FETCH_OK=0; fi
  TOP="$(git -C "$REPO" rev-parse --show-toplevel 2>/dev/null)"
  stray=0; cur="" br=""
  # iterate via a here-string so the loop runs in THIS shell (can bump $stray)
  while IFS= read -r line; do
    case "$line" in
      worktree\ *) cur="${line#worktree }";;
      branch\ *) br="${line#branch refs/heads/}"
        # skip the main checkout (its path == toplevel) — it's not a disposable worktree
        if [ -n "$br" ] && [ "$cur" != "$TOP" ] && git -C "$REPO" merge-base --is-ancestor "$br" "origin/$BASE" 2>/dev/null; then
          echo "  [FAIL] stray worktree on MERGED branch '$br' → $cur  (closeout prerequisites below)"; stray=$((stray+1))
        fi;;
    esac
  done <<< "$(git -C "$REPO" worktree list --porcelain 2>/dev/null)"
  if [ "$stray" -gt 0 ]; then fail "$stray stray linked worktree(s) — preserve results/evidence first; preserve unintegrated work; verify acceptance/integration and stop all writers, then follow agentctl/README.md closeout (otherwise retain and report)"; else ok "no linked worktree on a merged branch"; fi

  # 1b) base checkouts diverged from origin (post-squash shape: local side keeps the
  # pre-squash originals, upstream has the squashed result — ff can never happen again).
  # Detection + warn ONLY: the reset is the orchestrator's call (rescue真未合并的工作 first).
  # Ahead-only (unpushed local work, origin未动) deliberately does NOT warn — 宁钝勿敏.
  # A comparison that CANNOT run (fetch failed / ref missing) is UNKNOWN, never "aligned".
  div=0; unknown=0; seen=0
  while IFS= read -r line; do
    case "$line" in
      worktree\ *) cur="${line#worktree }";;
      branch\ *) br="${line#branch refs/heads/}"
        if [ "$br" = "$BASE" ]; then
          seen=$((seen+1))
          if [ "$FETCH_OK" = 1 ] && counts="$(git -C "$REPO" rev-list --left-right --count "origin/$BASE...$br" 2>/dev/null)"; then
            read -r behind ahead <<< "$counts"
            if [ "${ahead:-0}" -gt 0 ] && [ "${behind:-0}" -gt 0 ]; then
              # printf %q: the remedy is meant to be copy-pasted — literal quote-wrapping
              # is not a shell escape (a path containing a quote breaks out of it)
              qcur="$(printf '%q' "$cur")"; qref="$(printf '%q' "origin/$BASE")"
              echo "  [warn] base checkout '$cur' diverged from origin/$BASE (ahead $ahead / behind $behind) — squash-stale? verify content is merged, then: git -C $qcur branch backup/pre-realign && git -C $qcur reset --hard $qref"
              div=$((div+1))
            fi
          else
            echo "  [warn] base checkout '$cur': cannot compare with origin/$BASE (fetch failed / ref missing) — divergence UNKNOWN"
            unknown=$((unknown+1))
          fi
        fi;;
    esac
  done <<< "$(git -C "$REPO" worktree list --porcelain 2>/dev/null)"
  if [ $((div+unknown)) -gt 0 ]; then
    warn "$div diverged / $unknown UNKNOWN base checkout(s) — align after verifying (backup ref first)"
  elif [ "$seen" -eq 0 ]; then
    ok "no checkout on base branch '$BASE' to compare"
  else
    ok "base checkouts aligned with origin/$BASE"
  fi
fi

# 2–3) Status updates follow changed facts, not dates. Keep numbered slots for consumers.
echo "2) ACTIVE_CONTEXT 状态 (按事实更新,不判年龄):"
echo "  [skip] no mandatory snapshot rewrite; validate factual claims in check 10"
echo "3) roadmap 状态 (按事实更新,不判 mtime):"
echo "  [skip] completed change/test facts belong in Git/CI"

# 4) decision-queue sanity (opt-in — only if DECISION_QUEUE.md present)
echo "4) 决策队列 (仅活跃/待裁项,不判年龄):"
DQ="$DOCS/DECISION_QUEUE.md"
if [ -f "$DQ" ]; then
  cleared_history="$(awk '
    /^##[[:space:]]+/ {
      if (inside) exit
      upper=toupper($0)
      inside=(index($0, "✅") && (index(upper, "CLEARED") || index($0, "已清")))
      next
    }
    inside && $0 !~ /^[[:space:]]*$/ && $0 !~ /^[[:space:]]*<!--/ { print; exit }
  ' "$DQ")"
  if [ -n "$cleared_history" ]; then
    fail "DECISION_QUEUE.md retains cleared history — remove it before handoff/compact; git history is the audit trail"
  fi
  dq_bytes="$(wc -c < "$DQ" | tr -d ' ')"
  if [ "$dq_bytes" -gt 16384 ]; then
    warn "DECISION_QUEUE.md $dq_bytes bytes > 16384 — prune or archive resolved/stale entries"
  elif [ -z "$cleared_history" ]; then
    ok "decision queue contains active/parked items only"
  fi
else echo "  [skip] no $DQ (decision-queue 是 opt-in)"; fi

# 5) MEMORY.md size (soft)
echo "5) memory 治理 (索引行数 / 字节):"
if [ -n "$MEMORY" ] && [ -f "$MEMORY" ]; then
  n="$(wc -l < "$MEMORY" | tr -d ' ')"
  mem_bytes="$(wc -c < "$MEMORY" | tr -d ' ')"
  read -r mem_line mem_long < <(LC_ALL=C awk '
    NR==1 || length($0)>max { max=length($0); line=NR }
    END { print line+0, max+0 }
  ' "$MEMORY")
  mem_lines="$n lines (≤$MEMCAP)"
  [ "$n" -gt "$MEMCAP" ] && mem_lines="$n lines > $MEMCAP"
  mem_counts="MEMORY.md $mem_lines; $mem_bytes bytes (cap 12288); longest line $mem_line: $mem_long bytes (cap 512)"
  if [ "$n" -le "$MEMCAP" ] && [ "$mem_bytes" -le 12288 ] && [ "$mem_long" -le 512 ]; then
    ok "$mem_counts"
  else
    warn "$mem_counts"
  fi
elif [ -n "$MEMORY" ]; then warn "$MEMORY not found — skip"; else echo "  [skip] no --memory given"; fi

# 6) agent sessions of THIS repo left uncleaned — backstop for "terminal state ⇒
# agentctl stop" discipline (field 2026-07-28: 43 unstopped sessions leaked engines).
# FAIL = round believed over (terminal marker / rc recorded / wrapper dead) but control
# state remains; live mid-work sessions only warn (long-runners are legitimate).
echo "6) agent 会话收口 (本仓 duplex 会话: 终态必已 stop):"
AWDIR="${AGENT_WATCH_DIR:-/tmp/agent-watch-run}"
TOP="$(git -C "$REPO" rev-parse --show-toplevel 2>/dev/null)"
if [ -d "$AWDIR" ] && [ -n "$TOP" ]; then
  dead=0; live=0; livenames=""
  for m in "$AWDIR"/*.duplex.meta; do
    [ -e "$m" ] || continue
    mcwd="$(sed -n 's/^cwd=//p' "$m" | head -1)"
    # physical-path normalize: /tmp and /var are symlinks on macOS, and git toplevel
    # is already physical — a raw prefix match would silently skip those sessions
    mcwd="$(cd "$mcwd" 2>/dev/null && pwd -P || echo "$mcwd")"
    case "$mcwd" in "$TOP"|"$TOP"/*) ;; *) continue;; esac
    s="$(basename "$m" .duplex.meta)"
    # terminal evidence needs no tmux (marker / recorded rc); a dead wrapper only
    # counts when tmux is around to probe — without it, liveness is UNKNOWN, not dead.
    over=0
    { [ -e "$AWDIR/$s.terminal.json" ] || [ -e "$AWDIR/$s.duplex.rc" ]; } && over=1
    [ "$over" = 0 ] && command -v tmux >/dev/null 2>&1 \
      && ! tmux has-session -t "=$s" 2>/dev/null && over=1
    if [ "$over" = 1 ]; then
      echo "  [FAIL] session '$s' round is over but not stopped → agentctl stop $s"; dead=$((dead+1))
    else
      live=$((live+1)); livenames="$livenames $s"
    fi
  done
  if [ "$dead" -gt 0 ]; then fail "$dead 本仓终态会话未清 — agentctl stop 收口(引擎进程与控制态在泄漏)"
  else ok "no terminal-but-uncleaned session for this repo"; fi
  [ "$live" -gt 0 ] && warn "$live live/unknown session(s) of this repo still registered:$livenames — 逐个确认是有意长跑,其余 stop"
  # FOREIGN tmux sessions — live sessions matching NO recorded session. The comparison set
  # is EVERY recorded session (all repos, plus each `<s>-watchd` companion): filtering by
  # this repo's cwd would report other seats' legitimate sessions as foreign. Field
  # 2026-08-10: a seat with zero dispatch records read "clean up finished sessions" as a
  # bare `tmux ls` sweep and killed 6+ sessions owned by other seats. So: WARN ONLY —
  # never FAIL, never kill, and a session name is an exact string, never a shell pattern.
  known=""
  for m in "$AWDIR"/*.duplex.meta; do
    [ -e "$m" ] || continue
    known="$known$(basename "$m" .duplex.meta)
$(basename "$m" .duplex.meta)-watchd
"
  done
  if command -v tmux >/dev/null 2>&1; then
    tse="$(mktemp)"; tsout="$(tmux list-sessions -F '#{session_name}' 2>"$tse")"; trc=$?
    tsmsg="$(cat "$tse")"; rm -f "$tse"
    if [ "$trc" != 0 ]; then
      # no server = nobody home (silent); anything else is an UNCHECKED face, not a clean one
      case "$tsmsg" in
        *"no server running"*|*"error connecting to"*|*"no sessions"*) ;;
        *) warn "CHECKER-ERROR: tmux list-sessions rc=$trc (${tsmsg:-no message}) — FOREIGN 面未检查,别当 clean";;
      esac
    else
      foreign=""
      while IFS= read -r sname; do
        [ -n "$sname" ] || continue
        # quote each name: a session name may contain spaces, so an unquoted list would
        # read as more (or fewer) sessions than it names
        printf '%s\n' "$known" | grep -qxF -- "$sname" || foreign="$foreign \"$sname\""
      done < <(printf '%s\n' "$tsout")
      [ -n "$foreign" ] && warn "FOREIGN:$foreign — tmux 会话不在任何记录会话中(可能属他人/他席位):只报不杀,未经确认勿动"
    fi
  fi
else echo "  [skip] no agentctl run dir / not a git repo"; fi

# 7) typed lesson ledger — 教训要与门同形态 (retrospective.md §3): a lesson line is
# machine-countable data; prose lessons can't drive decisions and nobody counts their
# recurrences. Grammar (line start, optional "- " list marker):
#   LESSON: <slug> n=<int> gate=<none|accepted(<reason>)|<docs-repo-relative-or-absolute-path>>
# FAIL = n>=2 still gateless (a lesson may live as prose at most twice), or a claimed
# gate file that does not exist (a dead pointer reads as protection). No LESSON lines
# at all = ledger not adopted → note only: can't count what was never typed.
echo "7) 教训同形态 (LESSON 行: n≥2 须 gate 或显式 accepted):"
lessons=0; lfail=0
DOCS_ROOT="$(git -C "$DOCS" rev-parse --show-toplevel 2>/dev/null)"
while IFS= read -r ln; do
  lfile="${ln%%:*}"; body="${ln#*LESSON:}"
  lessons=$((lessons+1))
  # full-line grammar FIRST — a partially matching line is malformed, never partially
  # consumed (review-reproduced bypasses: 'n=1x' truncated to 1; an integer past the
  # shell test range erroring straight to green; prose after gate= read as a path).
  # slug is ASCII kebab/word chars; n is 1-9 digits (a cap, so [ -ge ] can't overflow).
  if ! printf '%s' "$body" | grep -qE '^[[:space:]]+[A-Za-z0-9_.-]+[[:space:]]+n=[0-9]{1,9}[[:space:]]+gate=[^[:space:]]'; then
    echo "  [warn] malformed LESSON line in $lfile — need 'LESSON: <slug> n=<int> gate=<none|accepted(reason)|path>'"
    warns=$((warns+1)); continue
  fi
  slug="$(printf '%s' "$body" | awk '{print $1}')"
  ln_n="$(printf '%s' "$body" | grep -oE ' n=[0-9]+' | head -1 | cut -d= -f2)"
  gate="$(printf '%s' "$body" | sed -n 's/.* gate=//p' | sed 's/[[:space:]]*$//')"
  case "$gate" in
    none)
      if [ "$ln_n" -ge 2 ]; then
        echo "  [FAIL] lesson '$slug' n=$ln_n gate=none — 复发≥2 还躺散文档:本批升门(gate=<path>)或主理人 accepted(理由)"
        lfail=$((lfail+1))
      fi;;
    none*)  # trailing prose after 'none' is not a path claim — reject, don't guess
      echo "  [warn] malformed LESSON line in $lfile — trailing text after gate=none"
      warns=$((warns+1));;
    accepted\(*\))
      reason="${gate#accepted(}"; reason="${reason%)}"
      if [ -z "$(printf '%s' "$reason" | tr -d '[:space:]')" ]; then
        echo "  [warn] lesson '$slug': accepted needs a reason — accepted(<why>)"; warns=$((warns+1))
      fi;;
    accepted*)
      echo "  [warn] lesson '$slug': accepted needs a reason — accepted(<why>)"; warns=$((warns+1));;
    *)
      case "$gate" in
        /*) gate_path="$gate";;
        *)
          if [ -z "$DOCS_ROOT" ]; then
            echo "  [FAIL] lesson '$slug': ERROR: docs Git root unresolved for '$DOCS' — gate verification UNKNOWN"
            lfail=$((lfail+1)); continue
          fi
          gate_path="$DOCS_ROOT/$gate";;
      esac
      if [ ! -e "$gate_path" ]; then
        echo "  [FAIL] lesson '$slug' claims gate '$gate' but no such file — dead pointer reads as protection"
        lfail=$((lfail+1))
      fi;;
  esac
done < <(find "$DOCS" -type d -name archive -prune -o -name '*.md' -type f -exec awk '
  FNR==1 { fence=0 }
  /^[[:space:]]*(```|~~~)/ { fence = !fence; next }
  fence { next }
  /^(- )?LESSON:/ { print FILENAME ":" $0 }
' {} + 2>/dev/null)
if [ "$lessons" -eq 0 ]; then
  echo "  [skip] no LESSON lines under $DOCS — 教训台账未 typed 化,复发计数不可机检(形态见 retrospective.md §3)"
elif [ "$lfail" -gt 0 ]; then
  fail "$lfail gateless/dead-pointer/UNKNOWN lesson(s) — 修路径、升门或 accepted 后再收口"
else
  ok "$lessons candidate LESSON line(s) checked for syntax/path existence; gate execution/effect unverified"
fi

# 8) gate-effect audit (GATE-AUDIT 行) — 形态与 FAIL 判据单源: retrospective.md §3「门效果审计」条。
echo "8) 门效果审计 (GATE-AUDIT 行: hits=0 且 false≥2 须 kill 或 keep(理由)):"
gaudits=0; gfail=0
while IFS= read -r ln; do
  gfile="${ln%%:*}"; body="${ln#*GATE-AUDIT:}"
  gaudits=$((gaudits+1))
  if ! printf '%s' "$body" | grep -qE '^[[:space:]]+[A-Za-z0-9_.-]+[[:space:]]+hits=[0-9]{1,9}[[:space:]]+false=[0-9]{1,9}[[:space:]]+action=(kill|keep(\(.*\))?)[[:space:]]*$'; then
    echo "  [warn] malformed GATE-AUDIT line in $gfile — need 'GATE-AUDIT: <slug> hits=<int> false=<int> action=<kill|keep(<reason>)>'"
    warns=$((warns+1)); continue
  fi
  gslug="$(printf '%s' "$body" | awk '{print $1}')"
  ghits="$(printf '%s' "$body" | grep -oE ' hits=[0-9]+' | head -1 | cut -d= -f2)"
  gfalse="$(printf '%s' "$body" | grep -oE ' false=[0-9]+' | head -1 | cut -d= -f2)"
  gaction="$(printf '%s' "$body" | sed -n 's/.* action=//p' | sed 's/[[:space:]]*$//')"
  case "$gaction" in
    kill) ;;
    keep\(*\))
      reason="${gaction#keep(}"; reason="${reason%)}"
      if [ -z "$(printf '%s' "$reason" | tr -d '[:space:]')" ] && [ "$ghits" -eq 0 ] && [ "$gfalse" -ge 2 ]; then
        echo "  [FAIL] gate '$gslug' hits=0 false=$gfalse kept with empty reason — 连续误报零战果默认删门,保留要写 keep(<why>)"
        gfail=$((gfail+1))
      fi;;
    keep)
      if [ "$ghits" -eq 0 ] && [ "$gfalse" -ge 2 ]; then
        echo "  [FAIL] gate '$gslug' hits=0 false=$gfalse action=keep — 连续误报零战果默认删门,保留要写 keep(<why>)"
        gfail=$((gfail+1))
      fi;;
  esac
done < <(find "$DOCS" -type d -name archive -prune -o -name '*.md' -type f -exec awk '
  FNR==1 { fence=0 }
  /^[[:space:]]*(```|~~~)/ { fence = !fence; next }
  fence { next }
  /^(- )?GATE-AUDIT:/ { print FILENAME ":" $0 }
' {} + 2>/dev/null)
if [ "$gaudits" -eq 0 ]; then
  echo "  [skip] no GATE-AUDIT lines under $DOCS — 本周期自造门未记账(形态见 retrospective.md §3)"
elif [ "$gfail" -gt 0 ]; then
  fail "$gfail zero-catch gate(s) kept without reason — 删门或 keep(理由) 后再收口"
else
  ok "$gaudits gate-audit line(s), no unjustified zero-catch gate"
fi

# 9) Advisory agentctl phases readings; no per-batch manual ledger requirement.
echo "9) 相位读数 (advisory,不要求人工记账):"
# Machine-time is input, not a judgement about avoidable cost. Missing/unknown coverage
# prints n/a and never changes PASS/FAIL. UTC phase rows use a local-offset cycle start.
PH_OFF="$(date +%z 2>/dev/null)"
case "$PH_OFF" in
  [+-][0-9][0-9][0-9][0-9]) PH_SINCE="${YDAY:-$TODAY}T00:00:00${PH_OFF%??}:${PH_OFF#???}" ;;
  *) PH_SINCE="" ;;
esac
if [ -z "$PH_SINCE" ]; then
  echo "  phases: n/a (date +%z gave no UTC offset — the cycle start cannot be spelled RFC3339)"
elif ! command -v agentctl >/dev/null 2>&1; then
  echo "  phases: n/a (agentctl not on PATH — no phase ledger to read)"
elif ! command -v python3 >/dev/null 2>&1; then
  echo "  phases: n/a (no python3 — the reading cannot be rendered)"
else
  PH_JSON="$(agentctl phases --json --since "$PH_SINCE" ${TOP:+--repo "$TOP"} 2>/dev/null)"
  printf '%s' "$PH_JSON" | python3 -c '
import json
import sys

raw = sys.stdin.read()
try:
    report = json.loads(raw)
except ValueError:
    print("  phases: n/a (agentctl phases produced no readable report)")
    raise SystemExit(0)
if not isinstance(report, dict):
    print("  phases: n/a (agentctl phases produced no readable report)")
    raise SystemExit(0)
if report.get("coverage") != "ok" and report.get("coverage") != "partial":
    # `unknown` — a missing shard, an UNREADABLE one (a directory wearing a shard name, a
    # dangling link, mode 000), an empty ledger, or a report from a version that does not
    # publish coverage at all. Every one of them means this pane cannot vouch for the window,
    # and a set of zeroes nobody measured looks exactly like a measurement.
    holes = ",".join(report.get("shards_missing") or []) or "-"
    dark = ",".join(report.get("shards_unreadable") or []) or "-"
    print("  phases: n/a (coverage unknown — shards missing %s, unreadable %s)"
          % (holes, dark))
    raise SystemExit(0)


def mins(seconds):
    return "n/a" if not isinstance(seconds, (int, float)) else "%.0fm" % (seconds / 60.0)


# Everything below indexes the documented report shape. A report that does not HAVE that shape
# degrades to n/a like every other unusable input: this pane is advisory, and a traceback in
# the middle of a retro is not an advisory.
try:
    read = report["readings"]
    lines = [
        "  MECHANICAL INPUT — DO NOT COPY AS VERDICT",
        "    coverage=%s  seats=%d  skipped=%d  clock_regressed=%d  future_dropped=%d"
        % (report["coverage"], len(report["sessions"]), report["skipped"],
           report["clock_regressed"], report.get("future_dropped", 0)),
        "    batch_span=%s  seat_wall=%s (seat machine-time, parallel seats sum above wall)"
        % (mins(read["batch_span_s"]), mins(read["seat_wall_s"])),
        "    review_wall=%s  idle_span=%s over %d gap(s)"
        % (mins(read["review_wall_s"]), mins(read["idle_span_s"]), read["idle_segments"]),
    ]
    for gap in read["idle_top"]:
        lines.append("      idle %s from %s" % (mins(gap["seconds"]), gap["from"]))
    hops = sorted(read["dispatch_latency"], key=lambda hop: hop["seconds"],
                  reverse=True)[:3]
    lines.append("    dispatch_latency max=%s (%d measured, per terminal — never summed)"
                 % (mins(read["dispatch_latency_max_s"]), len(read["dispatch_latency"])))
    for hop in hops:
        lines.append("      +%s after %s %s → %s %s"
                     % (mins(hop["seconds"]), hop["name"], hop["class"], hop["next_event"],
                        hop["next_name"]))
    lines.append("    ^ readings only; no manual accounting required.")
except (KeyError, TypeError, IndexError, ValueError):
    print("  phases: n/a (agentctl phases produced no readable report)")
    raise SystemExit(0)
print("\n".join(lines))
'
fi

# 10) 治理 claim 核账 (retrospective.md §5「状态维护」) — 治理文档里的事实句复盘时机械实跑。
# Re-run facts rather than treating a new timestamp as evidence.
# 形态与 goal 的继承断言单源 (goal-preflight.py 的 PREMISE 语法: `PREMISE: <claim>
# verify=\`cmd\` => rc=N count=N`), 这里只是换了消费者 — `--claims` 模式做形态 + 实跑 + 记号
# 比对, 不要求 Preflight 行、不判写集活树 (治理 claim 锚活世界正是它可证伪的原因)。
# opt-in: 文档里没有 PREMISE 行就跳过 — 没 typed 的事实句机检不了 (同第 7 / 8 检的口径)。
# 量具坏 = FAIL: claim 已 typed 却读不到脚本 / 没 python3, 这一面根本没检查。
# 未判 (超时 / 不可执行 / 非命令形态 / 无记号) 只透传 WARN, 从不算 DEAD: 本机跑不动一条命令,
# 说明不了那句事实。KILL CRITERION (GATE-AUDIT slug `doc-claims`): 连续两个复盘周期 0 DEAD
# 且 0 新增 claim ⇒ 降为教义。
echo "10) 治理 claim 核账 (治理文档 PREMISE 行实跑; opt-in):"
HERE="$(cd "$(dirname "$0")" && pwd)"
PREFLIGHT="$HERE/goal-preflight.py"
CLAIM_FILES=()
for cf in "$DOCS/ACTIVE_CONTEXT.md" "$DOCS/DECISION_QUEUE.md" "$DOCS/LESSONS.md"; do
  [ -f "$cf" ] || continue
  # a symlinked ACTIVE_CONTEXT is the field shape (a pointer into an archive): resolve it, so
  # the DEAD line names the file an editor will really change instead of the pointer
  if [ -L "$cf" ]; then
    tgt="$(readlink "$cf")"
    case "$tgt" in /*) cf="$tgt";; *) cf="$(dirname "$cf")/$tgt";; esac
    [ -f "$cf" ] || continue
  fi
  grep -l 'PREMISE' "$cf" >/dev/null 2>&1 || continue
  CLAIM_FILES+=("$cf")
done
if [ "${#CLAIM_FILES[@]}" -eq 0 ]; then
  echo "  [skip] no PREMISE claims in docs (opt-in)"
elif [ ! -f "$PREFLIGHT" ] || ! command -v python3 >/dev/null 2>&1; then
  fail "治理 claim 面未检查 — 量具坏 ($PREFLIGHT 或 python3 缺); claim 已 typed 却没跑 ≠ 绿"
else
  # doc paths resolve against the CALLER's cwd (that is where --docs was written), the probes
  # against the repo root (that is where a governance claim's relative path means anything)
  claim_out="$(GOAL_PREFLIGHT_CWD="${TOP:-$REPO}" python3 "$PREFLIGHT" \
    --claims "${CLAIM_FILES[@]}" 2>&1)"; claim_rc=$?
  [ -n "$claim_out" ] && printf '%s\n' "$claim_out"
  dead_n="$(printf '%s\n' "$claim_out" | grep -c '^DEAD:' | tr -d ' ')"
  if [ "$dead_n" -gt 0 ]; then
    fail "$dead_n dead claim(s) — 治理文档事实句实跑与声明不符; 改事实或改声明, 别只改时间戳"
  elif [ "$claim_rc" -ne 0 ]; then
    fail "PREMISE 声明形态未成立 (见上 ERR 行) — 占位符 / 未解的 claim 不是 claim"
  else
    ok "${#CLAIM_FILES[@]} 份治理文档的 PREMISE 行 0 DEAD"
  fi
fi

# 11) 文档年龄清单 (retrospective.md §5「文档归档」的机械半边) — 收口归档靠人记, 于是没人碰的
# 回执与陈旧段落永远活着。`doc-lifecycle.py` 只读扫描按 git 年龄出清单: 回执整份 TTL 天无触碰,
# 登记簿里无 `PREMISE:` 断言的段落 TTL 天无触碰。清单给人看, 搬与不搬人拍 —— 所以这一检只
# WARN, 从不 FAIL 在「有条目」上。判不了的形态 (不在仓 / dirty / living 缺) 由脚本列 skip 行。
# opt-in: 既无 archive 落点也无任何 living 登记簿 ⇒ 跳过 (同第 4 / 7 / 10 检的口径)。
# 量具坏 = FAIL: 脚本非 0 退出 (扫描面缺失 / 无 python3) 时这一面根本没检查, 而一个扫不到的面
# 不是一个干净的面。KILL CRITERION (GATE-AUDIT slug `doc-lifecycle`): 连续两个复盘周期清单非空
# 却一件没搬 ⇒ 这份清单没有消费者, 删。
echo "11) 文档年龄清单 (回执到期 / 无断言陈段; 只读, 只出清单):"
LIFECYCLE="$HERE/doc-lifecycle.py"
DOCFACE=0
[ -d "$DOCS/archive" ] && DOCFACE=1
ORCHSCAN=0
if [ "$(basename "$DOCS")" != orchestration ] && [ -d "$DOCS/orchestration" ]; then
  git -C "$DOCS" check-ignore -q orchestration 2>/dev/null; orch_ignore_rc=$?
  if [ "$orch_ignore_rc" -eq 1 ]; then
    ORCHSCAN=1
    [ -d "$DOCS/orchestration/archive" ] && DOCFACE=1
  fi
fi
for lf in "$DOCS/ACTIVE_CONTEXT.md" "$DOCS/DECISION_QUEUE.md" "$DOCS/LESSONS.md"; do
  [ -e "$lf" ] && DOCFACE=1
done
if [ "$DOCFACE" -eq 0 ]; then
  echo "  [skip] no $DOCS/archive and no living 登记簿 (doc-lifecycle 是 opt-in)"
else
  life_out="$(python3 "$LIFECYCLE" --docs "$DOCS" 2>&1)"; life_rc=$?
  if [ "$ORCHSCAN" -eq 1 ]; then
    orch_out="$(python3 "$LIFECYCLE" --docs "$DOCS/orchestration" --living "" 2>&1)"; orch_rc=$?
    life_out+=$'\n'"$orch_out"
    [ "$orch_rc" -ne 0 ] && life_rc="$orch_rc"
  fi
  life_exp="$(printf '%s\n' "$life_out" | grep -c '^expire:')"
  [ -n "$life_out" ] && printf '%s\n' "$life_out" | awk -v total="$life_exp" '
    /^expire:/ {
      n++; age=$NF; sub(/^age=/, "", age); sub(/d$/, "", age)
      if (age+0>oldest) oldest=age+0
      if (total>10 && n>5) next
    }
    { print "  " $0 }
    END { if (total>10) printf "  fold: %d expired total, oldest age=%dd (5 samples)\n", total, oldest }
  '
  life_n="$(printf '%s\n' "$life_out" | grep -c '^\(expire\|cool\):' | tr -d ' ')"
  if [ "$life_rc" -ne 0 ]; then
    fail "文档年龄面未检查 — 量具坏 ($LIFECYCLE rc=$life_rc); 扫不到 ≠ 干净"
  elif [ "$life_n" -gt 0 ]; then
    warn "$life_n 项待裁 (回执到期 / 陈段可降温) — 搬与不搬人拍, 机器只出清单"
  else
    ok "0 件到期, 0 段可降温"
  fi
fi

# 12) 会话经济 (retrospective.md §7「换会话」的读数半边) — 成本 = 上下文体量 × 请求数, 而一个
# 不换的编排会话把 400-550k 乘进它剩下的每一次请求。散文阈值没有读数就没人知道自己在哪一档:
# `session-economics.py --report` 只读本机该仓的 transcript, 按会话出 ctx/req 中位数 / 峰值 /
# 重缓存尖峰 / calls·msg / ro-streak, 一个字节都不改。提醒那一半在 retro-hooks.json 的
# UserPromptSubmit 触点, 与本检同一个脚本。
# opt-in: 本机没有该仓的 transcript 目录就跳过 (同第 4 / 7 / 10 / 11 检的口径)。只 WARN, 从不
# FAIL 在「贵」上——换不换会话是人拍, 机器只报数。量具坏 = FAIL: 脚本非 0 退出时这一面根本没
# 检查 (同第 10 / 11 检)。KILL CRITERION (GATE-AUDIT slug `ctx-nudge`, 30 天到 2026-10-23):
# 收到提醒的席位 ctx/req 中位数仍 >300k ⇒ 提醒等于散文, 撤; 连续两次复盘这份读数零讨论 ⇒ 删。
echo "12) 会话经济 (本仓会话 ctx/req 读数; opt-in):"
SESECON="$HERE/session-economics.py"
SE_TOP="$(git -C "$REPO" rev-parse --show-toplevel 2>/dev/null)"
[ -z "$SE_TOP" ] && SE_TOP="$REPO"
# harness 的 transcript 目录名 = cwd 里每个非 [A-Za-z0-9] 字符换成 `-`
SE_DIR="${HOME:-}/.claude/projects/$( (cd "$SE_TOP" 2>/dev/null && pwd -P) | sed 's/[^A-Za-z0-9]/-/g')"
if [ ! -d "$SE_DIR" ]; then
  echo "  [skip] 本机没有 $SE_DIR (无该仓 transcript)"
else
  se_out="$(python3 "$SESECON" --report "$SE_DIR" --days 14 2>&1)"; se_rc=$?
  [ -n "$se_out" ] && printf '%s\n' "$se_out" | sed 's/^/  /'
  se_over="$(printf '%s\n' "$se_out" | sed -n 's/.*over300k=\([0-9][0-9]*\).*/\1/p' | tail -1)"
  if [ "$se_rc" -ne 0 ]; then
    fail "会话经济面未检查 — 量具坏 ($SESECON rc=$se_rc); 读不到 ≠ 便宜"
  elif [ -n "$se_over" ] && [ "$se_over" -gt 0 ]; then
    warn "$se_over 个会话 ctx/req 中位数 >300k — 收口即 /compact (retrospective §7)"
  else
    ok "本周期无 ctx/req 中位数 >300k 的会话"
  fi
fi

echo "== result: $fails FAIL, $warns warn =="
[ "$fails" -eq 0 ]
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall