Skill: galexy/sageox-summary (version 0.3.1)

--- name: sageox-summary description: "Generate an overall team summary covering the last 24 hours across all SageOx-enabled teams. Reads distilled daily entries via `ox distill history` and produces a structured, Slack-ready overview." version: 0.3.1 metadata: { "openclaw": { "emoji": "📰", "os": ["macos", "linux"], "requires": { "bins": ["ox", "claude", "jq"] }, "install": [ { "id": "node-claude", "kind": "node", "package": "@anthropic-ai/claude-code", "bins": ["claude"], "label": "Install Claude Code CLI (npm)", }, { "id": "brew-jq", "kind": "brew", "formula": "jq", "bins": ["jq"], "label": "Install jq (brew)", }, ], "homepage": "https://sageox.ai", }, } --- # SageOx Summary You are an agent that generates a cross-team summary of the last 24 hours of SageOx distilled activity. You enumerate each team's recent distilled entries via `ox distill history`, inline their content into a prompt for `claude -p`, and return a structured Slack-formatted summary. This skill pairs with the [`sageox-distill`](https://clawhub.ai/skills/sageox-distill) skill — distill writes the source material, this skill synthesizes it. **ox version requirement:** this skill uses `ox distill history list` and `ox distill history show`, which landed in [PR #507](https://github.com/sageox/ox/pull/507). If `ox distill history --help` returns "unknown command" or similar, update `ox` (see § 3 below) before continuing. ## Prerequisites Before doing anything else, verify the user's environment. Run every check in order. If any required check fails, explain precisely what's missing and stop. Do not proceed until the user has fixed it. ### 1. Required binaries `ox`, `claude`, and `jq` are declared in the front matter's `requires.bins`, so OpenClaw checks them before running the skill. `claude` (npm) and `jq` (brew) have declarative installs in the front matter; `ox` does not. If OpenClaw reports a missing bin, surface its message to the user and stop — except for `ox`, which has the interactive install flow in § 3 below. `claude -p` will use whatever credentials `claude` already has — either an OAuth session from `claude login` (Pro/Max subscription) or `ANTHROPIC_API_KEY` exported in the shell that launched OpenClaw. The skill no longer accepts a per-skill `apiKey`. ### 2. Path validation rules Several steps below read a path from a JSON state file. Before interpolating any such value into a shell command, the agent **must** validate it against these rules: 1. **Absolute path required.** Must start with `/` or `~`. Reject relative paths and bare names. 2. **No `..` segments.** Reject anything containing `..`. 3. **No shell metacharacters.** Reject anything containing any of these characters: `;` `$` `` ` `` `|` `&` `<` `>` `(` `)` `{` `}` `*` `?` `[` `]` `!` `\` newline. On any validation failure: print a clear error to the user explaining which rule failed and ask them to provide a different path. **Do not attempt to "fix up" or sanitize the input** — reject and re-prompt. Treat values read from `~/.openclaw/memory/*.json` files as untrusted even though this skill writes them: the user (or a process running as the user) may have edited the file by hand or by another tool between runs. Re-validate every read. ### 3. Installing `ox` The `ox` CLI install state is recorded in `~/.openclaw/memory/sageox-ox-install.json`. On every run of this skill, invoke the bundled readiness gate: ```bash bash scripts/update-ox.sh ``` Contract: - **Stdout:** nothing on success - **Stderr:** on any failure, a two-line message — an `error:` line describing what's wrong, followed by a `fix:` line with the remediation. Surface both verbatim to the user. - **Exit:** `0` ox is pinned, installed, and reports the expected version (continue to § 4); `2` ox is not usable — one of: state file missing, binary missing at `$HOME/.local/bin/ox`, `ox` on PATH resolves to a different binary, binary fails to run, or binary reports a version other than the one recorded in `sageox-ox-install.json`. On exit `2`, STOP, read [`references/INSTALL.md`](references/INSTALL.md), follow the install flow, then re-run this script to confirm. There is no per-run auto-update. The curl install pins a specific `ox` release by tag and sha256; users pick up newer releases by re-running `clawhub install` for this skill after a new skill version publishes. The user can say **"reinstall ox"** at any time to re-enter the flow in [`references/INSTALL.md`](references/INSTALL.md). **Do not install `ox` via Homebrew or any package manager** (e.g. `brew install sageox/tap/ox`, `apt`, `dnf`, `pacman`). The tap exists for general use but is not supported inside OpenClaw skills — only the pinned-release curl flow is. ### 4. Authentication 1. `ox status` — confirm ox is authenticated. If not, tell the user to run `ox login` and try again. 2. Smoke-test `claude -p`: ```bash claude -p "say hi" --model claude-sonnet-4-6 ``` If it fails with an auth error, `claude` has no usable credentials. Tell the user to either run `claude login` (Pro/Max OAuth) or export `ANTHROPIC_API_KEY` in the shell that launches OpenClaw, then re-run the skill. The skill cannot inject the key itself. ## Configuration The skill uses two pieces of state: 1. **Repo manifest** — `~/.openclaw/memory/sageox-distill-repos.json` (shared with the `sageox-distill` skill). Format: ```json { "repos": [ { "path": "/home/user/repos/my-project", "team_id": "my-team" } ] } ``` The `team_id` values are what drive the summary — they're passed directly to `ox distill history list --team`. The `path` entries are not used by this skill, but stay in the manifest so `sageox-distill` keeps working. 2. **Summary state** — `~/.openclaw/memory/sageox-summary-state.json`. Tracks which distilled daily entry ids have already been included in a prior summary run so the skill never re-summarizes the same content. Shape: `{updated_at, teams: {<team_id>: {included_ids: [<id>, ...]}}}`. Missing file → empty state (first run). Treat contents as **untrusted**: every id must pass `^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9a-f-]+$` or be silently dropped. Both bundled scripts handle this already — the rule is stated here for anyone reading the state file directly. Pre-0.2.0 versions of this skill stored entries under `included_files` (with a `.md` suffix). That field is ignored by the current scripts; users upgrading from 0.1.x will re-summarize the most recent window once and the state file will converge to the new schema on the next successful run. If the manifest does not exist, tell the user to run the `sageox-distill` skill first to set up the repos, or ask for paths directly and populate it. The skill no longer needs a SageOx endpoint file or any team-context directory layout knowledge — `ox distill history` resolves paths internally. Earlier versions read `~/.openclaw/memory/sageox-endpoint.txt`; that file is ignored now and can be left alone or removed. ## Summary Pipeline When the user asks for a summary, run the steps in order. Steps 2 and 5 delegate their mechanics to `scripts/select-new-entries.sh` and `scripts/update-state.sh` (invoke via `bash scripts/<name>`). ### Step 1: Load the Manifest and Summary State 1. Read `~/.openclaw/memory/sageox-distill-repos.json` with `jq`. **Re-validate every `path` entry** against the Path validation rules in Prerequisites § 2 before using it — the manifest is user-writable and may have been hand-edited between runs. (The summary pipeline itself does not dereference the paths, but if the manifest looks corrupt we stop rather than guess at intent.) 2. Read `~/.openclaw/memory/sageox-summary-state.json` with `jq` if it exists. If it is **missing**, proceed silently as if the `teams` map were empty — first runs are normal. If it exists but is **malformed or unreadable**, proceed as if empty AND emit exactly one warning to **stderr**: ```text warning: sageox-summary-state.json was unreadable, starting from empty state ``` Never route this warning to stdout — stdout is the final summary (Step 6), and mixing decorative output into it breaks downstream consumers. This file is rewritten at the end of every successful run (see Step 5). 3. Collect the unique `team_id` values from the manifest. These drive every subsequent `ox distill history` call. ### Step 2: Select New Entries per Team The window is the last 24h, resolved server-side by `ox distill history list` against entry `created_at` timestamps. `ox` auto-expands the window around the UTC day boundary so runs don't miss yesterday's late entries — this skill passes `24h` verbatim and lets ox decide how wide to actually look. The state file then subtracts anything already summarized, so re-runs within the window are idempotent. First run (no state file) = every candidate is new, not an error. For each unique `team_id`, invoke `scripts/select-new-entries.sh`. It runs `ox distill history list --team <tid> --since 24h --layer daily --format json`, extracts the entry ids, and subtracts the team's `included_ids` set from the state file. Contract: - **Usage:** `select-new-entries.sh <team_id> <since> <state_file>` - **Stdout:** one entry id per line, sorted; empty if nothing new - **Stderr:** one-line warnings (malformed state, failed ox call) - **Exit:** `0` success (empty is not a failure; a failed ox call is treated as "no new entries" so the remaining teams still summarize), `2` usage, `3` internal (`jq` or `ox` missing) ```bash STATE_FILE=~/.openclaw/memory/sageox-summary-state.json NEW_IDS="$(bash scripts/select-new-entries.sh \ "$TEAM_ID" 24h "$STATE_FILE")" ``` Then: 1. If `NEW_IDS` is empty for a team, skip it this run — log `<team_id>: no new entries since last summary` to **stderr** and continue with the remaining teams. 2. If **every** team ends up with zero new entries, stop the pipeline before invoking Claude. Print one line to stdout — `No new distilled content since last summary.` — and exit. Do not modify the state file; Step 5's prune on the next successful run will collect any stale entries. ### Step 3: Fetch Entry Content and Build the Prompt For each team that survived Step 2, fetch the content of every new entry in a single `ox distill history show` call. `show` accepts multiple ids and emits each entry's markdown separated by its own `<!-- entry: <id> -->` header: ```bash # shellcheck disable=SC2086 TEAM_BLOCK="$(ox distill history show \ --team "$TEAM_ID" \ --format content \ $NEW_IDS)" ``` (Intentionally unquoted expansion: `NEW_IDS` is a sorted set of ids, each already matched against `^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9a-f-]+$` by Step 2, so word-splitting is safe and desired here.) If the `show` call fails for a team, surface the stderr and **stop the whole run** — partial summaries misrepresent the team's activity, and Step 5 stays untouched so the next run retries the same set. Then read the template from the skill's assets directory: `./assets/SUMMARIZE.md` (relative to this SKILL.md file). The file path on disk depends on where OpenClaw loaded the skill from — typically one of: - `~/.openclaw/skills/sageox-summary/assets/SUMMARIZE.md` - `./skills/sageox-summary/assets/SUMMARIZE.md` (workspace skill) Substitute template placeholders: - `{{ENTRIES}}` — one section per team that has a non-empty `NEW_IDS` set, in this format: ```text ### Team "<team_id>" <TEAM_BLOCK for that team> ``` Teams with zero new entries were already dropped in Step 2 and must not appear in `{{ENTRIES}}`. Do not re-number, re-wrap, or otherwise mutate the markdown inside `TEAM_BLOCK` — it is authored by `ox distill` and preserves the citation anchors Claude references in the final summary. - `{{MULTI_TEAM_RULES}}` — if **two or more** teams survived Step 2 with non-empty entry sets, replace with: ```text - Organize the summary by team, using each team ID as a section header - Attribute insights to the correct team ``` Otherwise, replace with an empty string. ### Step 4: Run Claude Invoke `claude -p` with the substituted prompt. The prompt already contains every entry's full text, so Claude does not need filesystem access — do **not** pass `--add-dir` and do **not** grant read tools. - `--model claude-sonnet-4-6` - No `--add-dir` (content is inline) - No `--allowedTools` (prompt is self-contained) - The substituted prompt passed via stdin `claude -p` will use whatever credentials `claude` already has — either an OAuth session from `claude login` or `ANTHROPIC_API_KEY` from the shell that launched OpenClaw (see Prerequisites § 1). Wrap the invocation in `timeout 600` (10 minutes) — this matches the timeout used by `pkg/sessionsummary/claude.go` in the `ox` repo for comparable Claude synthesis work and gives the model enough headroom for cross-team summaries that inline many daily entries: ```bash timeout 600 claude -p \ --model claude-sonnet-4-6 <<< "$PROMPT" ``` If the invocation fails (non-zero exit, timeout exit 124, network error), surface the error to the user and **do not** proceed to Step 5 — leaving the state file untouched lets the next run retry exactly the same candidate set. ### Step 5: Update Summary State Only run this step if Claude exited successfully. On any failure (non-zero exit, timeout, network error), skip it entirely — leaving the state file untouched lets the next run retry the same candidate set. For each team that had non-empty `NEW_IDS` in Step 2, pipe that team's ids into `scripts/update-state.sh`. The script merges them into the team's `included_ids`, prunes entries whose date prefix is strictly older than yesterday UTC (the candidate window, after ox's auto-expansion, spans at most today + yesterday), and writes the result atomically via a sibling temp file + `mv -f`. See the script header for full details; the short form: - **Usage:** `update-state.sh <state_file> <team_id>` - **Stdin:** one entry id per line (regex-filtered on read) - **Stdout:** nothing on success - **Stderr:** one-line warnings (e.g. malformed prior state) - **Exit:** `0` success, `2` usage, `3` internal ```bash printf '%s\n' "$NEW_IDS" \ | bash scripts/update-state.sh "$STATE_FILE" "$TEAM_ID" ``` Teams skipped in Step 2 are **not** invoked here — their prior state passes through unchanged because `update-state.sh` only rewrites the team_id it was given. Teams with no prior entry AND no new ids are correctly never added to the state file. ### Step 6: Return the Summary Return Claude's stdout to the user directly. It is already formatted for Slack mrkdwn. Do not reformat or annotate — just show it. ## Output The primary output is the Claude-generated summary. Prefix it with a brief one-line header showing: - How many teams were summarized - Any teams that were skipped (and why — typically "no new entries since last summary" from Step 2) Keep any preamble or postamble minimal. The summary itself is the value. If Step 2 short-circuited because every team had zero new entries, the only output is the single line `No new distilled content since last summary.` — do not invoke Claude and do not print a header.

path: assets/SUMMARIZE.md
content: # Team Summary

You are generating a team summary from a curated set of distilled session entries. The calling skill has already selected exactly which entries are new since the previous summary run and inlined each entry's full text below — you do not need to read any files and you have no filesystem access.

## Workflow

1. Synthesize the entries under `## Entries` below, grouped by team.
2. Entries are delimited by their `<!-- entry: <id> -->` header; treat that id as the citation anchor for anything you carry into the summary.
3. Produce a structured summary following the format described below.

## Entries

{{ENTRIES}}

## Summary structure

You MUST use exactly these four section headings. Each section should have 2–5 bullets. Prioritize signal over detail — a product manager and a marketer will read this alongside engineers. Synthesize across PRs and sessions; do not enumerate individual PRs unless they represent a meaningful milestone.

*Where we are*
Progress relative to what we set out to do. Cover both macro (goals, initiatives — are we on track?) and micro (what shipped recently). Name people and repos, but summarize themes rather than listing every PR.

*What's getting in the way*
Blockers, friction, unresolved issues, failed attempts, or things that took longer than expected. Flag patterns. This section drives the conversations the team needs to have.

*What we've learned*
This is one of the most valuable sections — don't skip or thin it out. Include: techniques or approaches someone used that others should adopt, non-obvious discoveries about the codebase or infrastructure, important team discussions and the conclusions reached, and shifts in thinking about how we build or ship. If someone solved a hard problem, explain the insight — not just that they fixed it.

*What's next*
Work queued up, drafts in progress, or follow-ups called out. Anything that signals upcoming changes others should prepare for.

## Formatting rules

- Format for Slack mrkdwn: use *bold*, _italic_, `code`, bullet points with •
- Keep it scannable — each bullet should be 1–2 sentences max
- Link to notable sessions where they add context
- Surface important discussions, debates, and decisions the team had
{{MULTI_TEAM_RULES}}


path: references/INSTALL.md
content: # Installing `ox`

Invoked when `bash scripts/update-ox.sh` exits `2` (no install state
recorded, or `ox` is not on PATH). The deterministic install shell lives
in `scripts/install-ox-curl.sh`; this file covers the user-facing flow
and PATH recovery.

## Install

Invoke the bundled helper. It downloads the `ox` release tarball
directly from GitHub Releases at a tag pinned in the script source,
verifies it against an sha256 checksum embedded in the script, extracts
it into `$HOME/.local/bin`, and records the install state (pinned
release tag, install directory, install timestamp) in
`~/.openclaw/memory/sageox-ox-install.json`. No sudo, no shell-script
piping, no dynamic "latest" resolution.

```bash
bash scripts/install-ox-curl.sh
```

Contract:

- **Args:** none
- **Stdout:** human-readable progress (download URL, checksum
  verification, extract, install dir)
- **Stderr:** errors and PATH-configuration guidance
- **Exit:** `0` success; `3` internal (curl/tar missing, download
  failed, checksum mismatch, unsupported platform, or `ox` not
  runnable after install)

**Do not install `ox` via Homebrew or any package manager** (e.g.
`brew install sageox/tap/ox`, `apt`, `dnf`, `pacman`). The tap exists
for general use but is not supported inside OpenClaw skills — only the
pinned-release curl flow is.

If the script exits non-zero, surface its stderr to the user and stop.
Do not silently retry.

## PATH configuration

`install-ox-curl.sh` installs into `$HOME/.local/bin`. This directory
is not on `PATH` by default on every distro. If the script prints a
warning to stderr that `$HOME/.local/bin` is not on `PATH`, surface its
guidance verbatim and ask the user to add the following line to
`~/.openclaw/.env`:

```sh
PATH=$HOME/.local/bin:$PATH
```

OpenClaw loads `.env` into the skill subprocess, so the updated `PATH`
takes effect on the next invocation. After the user confirms they've
updated the file, re-run the state checker to confirm `ox` is reachable:

```bash
bash scripts/update-ox.sh
```

It should exit `0` with no stderr.

## Upgrading `ox`

The curl flow pins a specific `ox` release by tag and sha256. There is
no per-run auto-update. To pick up a newer release, re-run
`scripts/install-ox-curl.sh` from a version of this skill that pins the
newer release — typically by re-running `clawhub install` for the
skill after a new skill version publishes.


path: scripts/install-ox-curl.sh
content: #!/usr/bin/env bash
# install-ox-curl.sh — download a pinned ox release binary directly from
# GitHub Releases, verify it against an embedded sha256 checksum, and
# install to $HOME/.local/bin. No sudo, no shell-script piping, no
# dynamic "latest" resolution.
#
# Why this shape: scanners flag `curl | bash` of a remote shell script,
# and skills that sudo into system paths. This script avoids both. The
# release tag and per-platform sha256s are pinned in the source below, so
# an attacker cannot substitute a different binary without also editing
# this file (which is reviewed on skill publish).
#
# Bumping: when a newer sageox/ox release ships, update OX_INSTALL_REF
# and the OX_SHA256_* constants. Fetch checksums.txt from
# https://github.com/sageox/ox/releases/download/<tag>/checksums.txt
#
# Usage: install-ox-curl.sh
#
# Stdout: human-readable progress
# Stderr: errors
# Exit:
#   0 — success, ox installed and memory file written
#   3 — internal error (curl/tar missing, download failed, checksum
#       mismatch, unsupported platform, or ox not runnable after install)

set -euo pipefail

OX_INSTALL_REF="v0.6.4"
OX_VERSION="${OX_INSTALL_REF#v}"
OX_REPO="sageox/ox"

# sha256(ox_<version>_<os>_<arch>.tar.gz) — from the checksums.txt asset
# on the pinned release. Lock these when bumping OX_INSTALL_REF.
OX_SHA256_darwin_amd64="a1e256a2ab1d1a3dfec5330ff9737be020a1ef36d133087f6c0b9e03255ddfe3"
OX_SHA256_darwin_arm64="91c36bd0bfec6651078394e3fdf300b78f2babcd8caf70eba436e3b6ea1c2bed"
OX_SHA256_linux_amd64="fe93cd0c093226c51347efe7dd9cd2d5bb055f3523e55a7b887eb2bc8d0312df"
OX_SHA256_linux_arm64="826c9d8eb8387cf029fad6f521a8be86887336e4fe89c97bae4708a99c218897"
OX_SHA256_freebsd_amd64="f1a5cc3c42675e5c1a10b299c0cae4e7407d5f18d722fc2a10009c9365c4ceb0"

command -v curl >/dev/null 2>&1 || { echo "error: curl is required" >&2; exit 3; }
command -v tar  >/dev/null 2>&1 || { echo "error: tar is required"  >&2; exit 3; }

case "$(uname -s)" in
  Darwin)  OS="darwin"  ;;
  Linux)   OS="linux"   ;;
  FreeBSD) OS="freebsd" ;;
  *)
    echo "error: unsupported OS $(uname -s); skill supports macOS, Linux, and FreeBSD" >&2
    exit 3
    ;;
esac

case "$(uname -m)" in
  x86_64|amd64)  ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *)
    echo "error: unsupported architecture $(uname -m)" >&2
    exit 3
    ;;
esac

PLATFORM="${OS}_${ARCH}"
SHA_VAR="OX_SHA256_${PLATFORM}"
EXPECTED_SHA="${!SHA_VAR:-}"
if [ -z "$EXPECTED_SHA" ]; then
  echo "error: no pinned checksum for platform ${PLATFORM} in ${OX_INSTALL_REF}" >&2
  exit 3
fi

ARCHIVE_NAME="ox_${OX_VERSION}_${PLATFORM}.tar.gz"
DOWNLOAD_URL="https://github.com/${OX_REPO}/releases/download/${OX_INSTALL_REF}/${ARCHIVE_NAME}"

# Portable mktemp template — works on both GNU (Linux) and BSD (macOS).
WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ox-install.XXXXXXXX")"
trap 'rm -rf "$WORK_DIR" 2>/dev/null' EXIT

echo "Downloading ox ${OX_INSTALL_REF} for ${PLATFORM}"
echo "  from: ${DOWNLOAD_URL}"

# -f fails on HTTP errors, --max-time bounds a stalled connection.
if ! curl -fsSL --max-time 120 "$DOWNLOAD_URL" -o "$WORK_DIR/$ARCHIVE_NAME"; then
  echo "error: failed to download ${DOWNLOAD_URL}" >&2
  exit 3
fi

echo "Verifying sha256 checksum..."
if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL_SHA="$(sha256sum "$WORK_DIR/$ARCHIVE_NAME" | awk '{print $1}')"
elif command -v shasum >/dev/null 2>&1; then
  ACTUAL_SHA="$(shasum -a 256 "$WORK_DIR/$ARCHIVE_NAME" | awk '{print $1}')"
else
  echo "error: neither sha256sum nor shasum is available; refusing to install unverified binary" >&2
  exit 3
fi

if [ "$ACTUAL_SHA" != "$EXPECTED_SHA" ]; then
  echo "error: sha256 mismatch for ${ARCHIVE_NAME}" >&2
  echo "  expected: $EXPECTED_SHA" >&2
  echo "  actual:   $ACTUAL_SHA" >&2
  exit 3
fi
echo "  ok: $ACTUAL_SHA"

echo "Extracting archive..."
if ! tar -xzf "$WORK_DIR/$ARCHIVE_NAME" -C "$WORK_DIR"; then
  echo "error: failed to extract $ARCHIVE_NAME" >&2
  exit 3
fi

INSTALL_DIR="$HOME/.local/bin"
mkdir -p "$INSTALL_DIR"

# Install ox and every ox-adapter-* binary shipped in the tarball. We
# glob rather than hardcode the adapter list so new adapters added in
# future releases work without re-editing this file.
shopt -s nullglob
installed=0
for src in "$WORK_DIR/ox" "$WORK_DIR"/ox-adapter-*; do
  [ -f "$src" ] || continue
  name="$(basename "$src")"
  dest="$INSTALL_DIR/$name"
  mv "$src" "$dest"
  chmod +x "$dest"

  # macOS ad-hoc re-sign: avoids slow Gatekeeper checks on first run.
  # Non-fatal — a failure here does not block install.
  if [ "$OS" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
    codesign --remove-signature "$dest" 2>/dev/null || true
    codesign --force --sign - "$dest" 2>/dev/null || true
  fi

  installed=$((installed + 1))
done
shopt -u nullglob

if [ "$installed" -eq 0 ]; then
  echo "error: tarball contained no ox binaries" >&2
  exit 3
fi

echo "Installed $installed binaries to $INSTALL_DIR"

# PATH guidance — $HOME/.local/bin isn't on PATH by default on every
# distro. Surface this before the readiness gate so the user sees the
# fix in context.
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  echo ""
  echo "warning: $INSTALL_DIR is not on your PATH" >&2
  echo "fix: add this line to ~/.openclaw/.env (OpenClaw loads it into the skill subprocess):" >&2
  echo "  PATH=\"$INSTALL_DIR:\$PATH\"" >&2
  echo "then restart the skill." >&2
fi

# Readiness gate: the binary at $INSTALL_DIR/ox must exist, be
# executable, run, and report the pinned release version. The sha256
# check earlier guarantees the extracted bytes are exactly what GitHub
# Releases published for this tag, but those bytes might still fail to
# execute on the host (libc mismatch, unsupported OS version, stripped
# dependency, etc.) — catch that now, before we write state claiming a
# successful install.
#
# Invoke the literal $INSTALL_DIR/ox path rather than using PATH
# lookup. If for any reason the install loop above didn't actually
# write the ox binary (e.g. a future tarball ships only adapters, or
# the upstream release was mis-packaged), a PATH-based check could
# silently fall through to a pre-existing system ox and claim success
# against the wrong binary.
if [ ! -x "$INSTALL_DIR/ox" ]; then
  echo "error: expected ox binary missing at $INSTALL_DIR/ox" >&2
  exit 3
fi

if ! version_output="$("$INSTALL_DIR/ox" version 2>&1)"; then
  echo "error: $INSTALL_DIR/ox failed to run" >&2
  echo "$version_output" >&2
  exit 3
fi

# `ox version` prints "ox <version>\n..." on stdout. Compare the first
# line exactly rather than substring-matching — a loose *"$OX_VERSION"*
# pattern would false-positive when e.g. 0.6.3 is a suffix of 10.6.3.
first_line="$(printf '%s\n' "$version_output" | head -n1)"
if [ "$first_line" != "ox $OX_VERSION" ]; then
  echo "error: $INSTALL_DIR/ox reports '$first_line', expected 'ox $OX_VERSION'" >&2
  exit 3
fi

# Record install state so update-ox.sh can confirm the skill has a
# known-good ox install on subsequent runs. Only factual state — what
# was installed, where, when — no preference fields.
#
# Use `jq -n --arg` rather than a heredoc so JSON-special characters in
# values (e.g. `"` or `\` in a pathological $HOME) get escaped correctly
# instead of producing a malformed state file. `jq` is a hard skill
# dependency (declared in SKILL.md `requires.bins`), so OpenClaw has
# already ensured it's available by the time this script runs.
#
# Write to a temp file in the same directory, then rename into place.
# update-ox.sh reads this file, so an interrupted write that left a
# zero-byte or partial JSON file would break the readiness gate.
# Same-directory rename is atomic at the directory-entry level, which
# is all we need here.
STATE_DIR="$HOME/.openclaw/memory"
STATE_FILE="$STATE_DIR/sageox-ox-install.json"
mkdir -p "$STATE_DIR"
TMP_STATE_FILE="$(mktemp "${STATE_DIR}/sageox-ox-install.json.XXXXXXXX")"
INSTALLED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
jq -n \
  --arg ox_install_ref "$OX_INSTALL_REF" \
  --arg install_dir    "$INSTALL_DIR" \
  --arg installed_at   "$INSTALLED_AT" \
  '{
    ox_install_ref: $ox_install_ref,
    install_dir:    $install_dir,
    installed_at:   $installed_at
  }' > "$TMP_STATE_FILE"
mv "$TMP_STATE_FILE" "$STATE_FILE"

echo "ox ${OX_INSTALL_REF} installed successfully"


path: scripts/select-new-entries.sh
content: #!/usr/bin/env bash
# select-new-entries.sh — print ox distill history entry ids for a team
# that fall within the --since window and have NOT yet been included in a
# prior summary run.
#
# Usage: select-new-entries.sh <team_id> <since> <state_file>
#
# Arguments:
#   <team_id>     Team slug, id, or name. Passed verbatim to
#                 `ox distill history list --team`, and used as the key
#                 inside the state file's .teams map.
#   <since>       Window duration (e.g. 24h). Passed verbatim to
#                 `--since`. Anything ox's flag parser accepts works.
#                 ox auto-expands the window around the UTC day
#                 boundary, so `24h` is the pipeline's default.
#   <state_file>  Absolute path to sageox-summary-state.json (need not
#                 exist — a missing file is treated as empty state).
#
# Stdout: one entry id per line, sorted ascending. Empty if nothing new.
# Stderr: single-line warnings (malformed state, failed ox call).
# Exit:
#   0 — success (empty output is not a failure, including when the ox
#       call fails — the caller skips the team and continues)
#   2 — usage error
#   3 — internal error (required tool missing)

set -euo pipefail

if [ $# -ne 3 ]; then
  echo "usage: $(basename "$0") <team_id> <since> <state_file>" >&2
  exit 2
fi

TEAM_ID="$1"
SINCE="$2"
STATE_FILE="$3"

command -v jq >/dev/null 2>&1 || { echo "error: jq is required" >&2; exit 3; }
command -v ox >/dev/null 2>&1 || { echo "error: ox is required" >&2; exit 3; }

ID_RE='^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9a-f-]+$'

# Ask ox which distilled daily entries fall in the window. We pin the
# layer to `daily` because weekly/monthly roll-ups would double-count
# material the summary already synthesized from the daily layer.
CANDIDATES=""
if OX_OUT="$(ox distill history list \
  --team "$TEAM_ID" \
  --since "$SINCE" \
  --layer daily \
  --format json 2>/dev/null)"; then
  CANDIDATES="$(
    printf '%s' "$OX_OUT" \
      | jq -r '.data.entries[]?.id // empty' 2>/dev/null \
      | grep -E "$ID_RE" \
      | sort -u || true
  )"
else
  echo "warning: ox distill history list failed for team $TEAM_ID" >&2
fi

# Already-summarized set for this team. Missing state → empty
# (first run). Malformed → empty + stderr warning.
ALREADY_INCLUDED=""
if [ -f "$STATE_FILE" ]; then
  if ! jq -e . "$STATE_FILE" >/dev/null 2>&1; then
    echo "warning: $STATE_FILE was unreadable, starting from empty state" >&2
  else
    ALREADY_INCLUDED="$(
      jq -r --arg tid "$TEAM_ID" \
        '.teams[$tid].included_ids[]? // empty' "$STATE_FILE" \
      | grep -E "$ID_RE" \
      | sort -u || true
    )"
  fi
fi

# Set difference: CANDIDATES − ALREADY_INCLUDED. Both sides are already
# sorted and regex-validated; temp files avoid multi-line `awk -v`
# quirks on BSD.
CAND_TMP="$(mktemp)"
INCL_TMP="$(mktemp)"
trap 'rm -f "$CAND_TMP" "$INCL_TMP" 2>/dev/null' EXIT

printf '%s\n' "$CANDIDATES"       | grep -v '^$' > "$CAND_TMP" || true
printf '%s\n' "$ALREADY_INCLUDED" | grep -v '^$' > "$INCL_TMP" || true

comm -23 "$CAND_TMP" "$INCL_TMP"


path: scripts/update-ox.sh
content: #!/usr/bin/env bash
# update-ox.sh — "is the pinned ox install usable?" readiness gate for
# every invocation of this skill.
#
# Reads ~/.openclaw/memory/sageox-ox-install.json to confirm the install
# state exists, then verifies that `ox` on PATH resolves to the pinned
# install at $HOME/.local/bin/ox. A bare `command -v ox` is insufficient:
# if an older system ox (e.g. /usr/local/bin/ox) appears before
# $HOME/.local/bin on PATH, `command -v` would silently resolve to it
# and defeat the pinned-release contract. The curl install path has no
# per-run update — users re-run install-ox-curl.sh to bump the pinned
# release.
#
# Usage: update-ox.sh
#
# Stdout: nothing on success
# Stderr: one-line "needs install", "not at pinned path", or "PATH
#         order wrong" signal
# Exit:
#   0 — pinned ox is ready, agent should proceed to the next prerequisite
#   2 — ox is not usable (no state file, binary missing at pinned path,
#       or PATH resolves to a different ox); agent must read
#       references/INSTALL.md and run the install flow before continuing

set -euo pipefail

STATE_FILE="$HOME/.openclaw/memory/sageox-ox-install.json"
EXPECTED_OX="$HOME/.local/bin/ox"

if [ ! -f "$STATE_FILE" ]; then
  echo "ox install state not configured — run install flow from references/INSTALL.md" >&2
  exit 2
fi

# The pinned install must actually exist at the expected path. Anything
# else (deleted, wrong permissions, never installed by this skill) means
# the state file is stale and the install flow needs to be re-run.
if [ ! -x "$EXPECTED_OX" ]; then
  echo "error: ox is not installed at $EXPECTED_OX" >&2
  echo "fix: re-run the install flow from references/INSTALL.md" >&2
  exit 2
fi

# `command -v` must resolve to the pinned install — not some other ox
# earlier on PATH. If an older system install shadows the pinned one,
# running the skill against it would defeat the whole point of the
# pinned-release contract, so fail with a PATH-order hint.
resolved_ox="$(command -v ox 2>/dev/null || true)"
if [ "$resolved_ox" != "$EXPECTED_OX" ]; then
  echo "error: 'ox' resolves to '${resolved_ox:-<not on PATH>}', not $EXPECTED_OX" >&2
  echo "fix: prepend \$HOME/.local/bin to PATH in ~/.openclaw/.env so the pinned install wins" >&2
  exit 2
fi

# Verify the binary itself still reports the pinned version. The path
# check above proves PATH order is right; this check proves the bytes
# behind the path haven't been replaced or corrupted since install.
# `jq` is required by the skill (see SKILL.md § 2), so it's guaranteed
# present by the time this script runs.
expected_ref="$(jq -r '.ox_install_ref // empty' "$STATE_FILE" 2>/dev/null || true)"
if [ -z "$expected_ref" ]; then
  echo "error: $STATE_FILE is missing ox_install_ref" >&2
  echo "fix: re-run the install flow from references/INSTALL.md" >&2
  exit 2
fi
expected_version="${expected_ref#v}"

if ! version_output="$("$EXPECTED_OX" version 2>&1)"; then
  echo "error: $EXPECTED_OX failed to run" >&2
  echo "$version_output" >&2
  echo "fix: re-run the install flow from references/INSTALL.md" >&2
  exit 2
fi

first_line="$(printf '%s\n' "$version_output" | head -n1)"
if [ "$first_line" != "ox $expected_version" ]; then
  echo "error: $EXPECTED_OX reports '$first_line', expected 'ox $expected_version'" >&2
  echo "fix: re-run the install flow from references/INSTALL.md" >&2
  exit 2
fi

exit 0


path: scripts/update-state.sh
content: #!/usr/bin/env bash
# update-state.sh — atomically merge a set of newly-summarized entry ids
# into the per-team included_ids list, prune stale entries, and write
# the result back via a temp-file rename.
#
# Usage: update-state.sh <state_file> <team_id>
#        (reads newline-separated entry ids from stdin)
#
# Arguments:
#   <state_file>  Absolute path to sageox-summary-state.json
#   <team_id>     Team id key to merge under
#
# Stdin: one entry id per line (may be empty). Lines not matching the
# distill-output id regex are silently dropped.
#
# Stdout: nothing on success.
# Stderr: single-line warnings (e.g. malformed prior state).
# Exit:
#   0 — success
#   2 — usage error
#   3 — internal error (required tool missing, write failed)

set -euo pipefail

if [ $# -ne 2 ]; then
  echo "usage: $(basename "$0") <state_file> <team_id>" >&2
  exit 2
fi

STATE_FILE="$1"
TEAM_ID="$2"

command -v jq >/dev/null 2>&1 || { echo "error: jq is required" >&2; exit 3; }

ID_RE='^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9a-f-]+$'

# Prune cutoff: drop entries whose date prefix is strictly older than
# YESTERDAY_UTC. `ox distill history list --since 24h` auto-expands its
# window around the day boundary, so the candidate set spans at most
# today + yesterday UTC; keeping state at `>= yesterday` guarantees no
# id in range is ever dropped. BSD `date` uses `-v`; GNU uses `-d`.
CUTOFF_UTC="$(date -u -v-1d +%Y-%m-%d 2>/dev/null \
  || date -u -d 'yesterday' +%Y-%m-%d)"
NOW_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

# Read and regex-filter added entry ids from stdin.
ADDED="$(grep -E "$ID_RE" || true)"

# Load existing state. Missing → {}. Malformed → {} + stderr warning.
if [ -f "$STATE_FILE" ]; then
  if ! EXISTING="$(jq -c . "$STATE_FILE" 2>/dev/null)"; then
    echo "warning: $STATE_FILE was unreadable, starting from empty state" >&2
    EXISTING='{}'
  fi
else
  EXISTING='{}'
fi

# Merge + prune + dedupe in a single jq pass. Preserves other teams'
# entries verbatim — only the target team's included_ids is rewritten.
NEW_STATE="$(
  jq -n \
    --argjson existing "$EXISTING" \
    --arg tid "$TEAM_ID" \
    --arg added "$ADDED" \
    --arg cutoff "$CUTOFF_UTC" \
    --arg now "$NOW_UTC" \
    --arg re "$ID_RE" \
    '
      ($existing // {}) as $e
    | ($e.teams // {}) as $teams
    | ($teams[$tid].included_ids // []) as $prior
    | ($added | split("\n") | map(select(. != ""))) as $new
    | (($prior + $new)
        | map(select(test($re)))
        | map(select(.[0:10] >= $cutoff))
        | unique
      ) as $merged
    | $e
      | .teams = ($teams | .[$tid] = {included_ids: $merged})
      | .updated_at = $now
    '
)"

# Atomic write: temp file in the same directory, then rename.
STATE_DIR="$(dirname "$STATE_FILE")"
mkdir -p "$STATE_DIR"
TMP_FILE="${STATE_FILE}.tmp.$$"
trap 'rm -f "$TMP_FILE" 2>/dev/null' EXIT
printf '%s\n' "$NEW_STATE" > "$TMP_FILE"
mv -f "$TMP_FILE" "$STATE_FILE"


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)