Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

31.3 KB
Raw Blame
#!/bin/bash
# The raea skill's generated references (docs/skills.feature SK1-SK2): the hand-written core, skills/skills/raea/SKILL.md
# (the raea-skills submodule, where the raea skill lives),
# links these instead of repeating them, so a verb, a flag, a feed tool or an export changes its reference in the
# same commit.
#
#   tools/skills.sh gen     write skills/skills/raea/reference/{cli,feed,files,sdk,app,platforms}.md, and copy the craft guides
#                           (sdk/guides/craft, what `raea guide` prints) into the skill (copies() below: bevy/ as 3d/,
#                           motion.md and motion/, and the router, floor, rubric, modes/, verbs/ and checks/ under craft/), so a
#                           clone of raea-skills reads whole without raea; commit them in raea-skills, then the pointer here
#   tools/skills.sh check   the drift gate (SK3, in L0): fails on a stale reference, a retired word, a flag a verb
#                           doesn't take, a RAEA_* variable nothing reads, or a relative link that goes nowhere, each
#                           with its file, line and fix. engine/cli/conformance/surface.test.ts checks the verbs and
#                           guides named, and tools/context-examples.sh the examples; this doesn't repeat them.
#                           It also warns (SK4) when a change touches a source a section names in its
#                           `<!-- sources: PATH ... -->` line and leaves the section alone: the landing message answers
#                           it ("checked, still true", or the edit). SKILLS_CHANGED lists the changed files (L0 passes
#                           its own); else the changes since origin/main.
#                           SKILLS_STRICT=1 (tools/release.sh) is a release's check: RAEA_BIN is the release's own
#                           build of this tree, so its help is the truth and every difference fails.
#   tools/skills.sh check-cli  cli.md against RAEA_BIN's help alone, with no feed app: tools/release.sh on a public
#                           checkout, where RAEA_BIN is the release's own build
#   tools/skills.sh coverage  each verb, SDK entry and feed tool, and how many a guide or the skill teaches (coverage() below);
#                           check warns on each one untaught
#   tools/skills.sh stale   every section with sources, by how many commits to them it has missed since it last changed
#
# Sources: cli.md from `raea help --json` (engine/cli/src/usage.rs); feed.md from FEED_TOOLS (apps/app
# src/acp/protocol.ts), with each tool's access tag; files.md from a workspace and project raea makes in a scratch
# folder, and the ~/.raea paths engine/cli and the feed's host name; sdk.md from the exports of each sdk/raea/src entry.
# RAEA_BIN picks the raea (default: this checkout's target/debug/raea, else target/release/raea, else PATH); where the
# feed app is read from, tools/skills-app.sh.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
SK=skills/skills
OUT=${SKILLS_OUT:-$SK/raea/reference}
# where gen-into puts the copied guides (copies() names them relative to it): the skill itself, or a scratch folder
COPY_OUT=${SKILLS_COPY_OUT:-$SK/raea}
# the guides the skill carries, each as SOURCE<TAB>COPY (COPY relative to the skill): `raea guide NAME` prints the source,
# and the skill's routers (3d.md, and one per domain in raea-skills) link the copy. Skill-only files beside the copies
# (3d/plugins.md, 3d/rows.md) aren't listed.
copies() {
  local g
  for g in sdk/guides/craft/bevy/*.md sdk/guides/craft/bevy/NOTICE; do printf '%s\t3d/%s\n' "$g" "${g##*/}"; done
  printf '%s\tmotion.md\n' sdk/guides/craft/motion.md
  for g in sdk/guides/craft/motion/*.md; do printf '%s\tmotion/%s\n' "$g" "${g##*/}"; done
  for g in ROUTER.md floor.md rubric.md NOTICE; do printf '%s\tcraft/%s\n' "sdk/guides/craft/$g" "$g"; done
  # building anything as components (raea guide components; docs/components.md): at the skill's root, beside its routers
  printf '%s\tcomponents.md\n' sdk/guides/craft/components.md
  for g in sdk/guides/craft/modes/*.md; do printf '%s\tcraft/modes/%s\n' "$g" "${g##*/}"; done
  for g in sdk/guides/craft/verbs/*.md; do printf '%s\tcraft/verbs/%s\n' "$g" "${g##*/}"; done
  # stories as data (raea/story): the router, how to write, check, sample and score, and a page per framework
  for g in sdk/guides/craft/story/*.md; do printf '%s\tcraft/story/%s\n' "$g" "${g##*/}"; done
  # the worked checks a note's ask copies into its project (DR6): each a raea/check system with its values and cheats
  for g in sdk/guides/craft/checks/*.ts; do printf '%s\tcraft/checks/%s\n' "$g" "${g##*/}"; done
  # the match-cut kit a storyboard's chain copies into its project (raea guide match-cuts): chain, plan, thirds, board
  for g in sdk/guides/craft/match-cuts/*; do printf '%s\tcraft/match-cuts/%s\n' "$g" "${g##*/}"; done
}
# the folders whose every file is a copy (a file there with no source is one whose guide was removed or renamed)
COPY_DIRS="3d motion craft craft/modes craft/verbs craft/story craft/checks craft/match-cuts"
SKILL_ONLY="3d/plugins.md 3d/rows.md"
HEAD_LINE="<!-- generated by tools/skills.sh gen; do not edit -->"
# the feed app: APP, APP_REV, app_show and app_grep
. "$ROOT/tools/skills-app.sh"

raea_bin() {
  if [ -n "${RAEA_BIN:-}" ]; then echo "$RAEA_BIN"
  elif [ -x target/debug/raea ] && [ target/debug/raea -nt target/release/raea ]; then echo "$ROOT/target/debug/raea"
  elif [ -x target/release/raea ]; then echo "$ROOT/target/release/raea"
  else command -v raea; fi
}

gen_cli() {
  "$R" help --json | jq -r --arg head "$HEAD_LINE" '
    $head, "",
    "# raea CLI",
    "",
    "Every verb `raea help` lists, with its forms, its flags (and how many values follow each) and where it runs:",
    "HEADLESS needs nothing running; HOST needs the raea app'"'"'s host; PERSON waits on a click. A verb refuses a flag",
    "or an argument its usage doesn'"'"'t name, so these lists are what it takes.",
    "",
    (.verbs[] |
      "## raea \(.verb)", "",
      "Access: \(.access). " + (if .own_parser then "Its arguments go to a parser of its own: `raea \(.verb)` alone lists them." else "Arguments besides flags: \(if .args == null then "any number" else .args end)." end), "",
      "```", (.usage[]), "```", "",
      (if (.flags | length) > 0 then
        ("Flags: " + ([.flags[] | "`\(.flag)`" + (if .values > 0 then " (\(.values))" else "" end)] | join(", ")) + "."), ""
       else empty end))'
}

gen_platforms() {
  # the app's publishing guidelines (apps/app src/publish/specs.ts at the recorded commit; it imports nothing)
  local p; p=$(mktemp -d "${TMPDIR:-/tmp}/skills-platforms.XXXXXX")
  app_show src/publish/specs.ts > "$p/specs.ts"
  bun -e '
    const { SPECS } = await import(process.argv[1] + "/specs.ts")
    console.log(JSON.stringify(Object.entries(SPECS).filter(([, s]) => s.aspects.length).map(([name, s]) => ({ name, ...s }))))
  ' "$p" | jq -r --arg head "$HEAD_LINE" '
    def secs: if . == null then "" elif . >= 3600 and . % 3600 == 0 then "\(. / 3600) h" elif . >= 60 and . % 60 == 0 then "\(. / 60) min" else "\(.) s" end;
    def size: if . == null then "" elif . >= 1073741824 then "\(. / 1073741824) GB" else "\(. / 1048576) MB" end;
    def pct: (. * 100 | round | tostring) + "%";
    $head, "",
    "# Platforms",
    "",
    "What each network the raea app publishes to shows and takes, from the app'"'"'s publishing guidelines (apps/app",
    "src/publish/specs.ts): the Publish view checks a post against them before it goes. Shapes are w:h, the first the",
    "one the network is made for. Length is the shortest and longest it takes, and the length its feed favours. The",
    "safe zone is how much of a vertical frame its own buttons, caption and profile row cover on a phone, from each",
    "edge: keep text and faces out of it (`raea check --platform` measures it).",
    "",
    "| network | shapes | length | favours | file | caption | hashtags | links in caption | safe zone (top, bottom, left, right) |",
    "|---|---|---|---|---|---|---|---|---|",
    (.[] | "| \(.name) | \(.aspects | join(", ")) | \(if .minDuration and .maxDuration then "\(.minDuration | secs) to \(.maxDuration | secs)" elif .maxDuration then "up to \(.maxDuration | secs)" else "" end) | \(.sweetSpot | secs) | \(.maxBytes | size) | \(.caption)\(if .graphemes then " graphemes" else " chars" end) | \(if .hashtags then ([(if .hashtags.advice then "\(.hashtags.advice[0])-\(.hashtags.advice[1]) advised" else empty end), (if .hashtags.max then "\(.hashtags.max) max" else empty end)] | join(", ")) elif .topicTags then "\(.topicTags) topic tag" else "" end) | \(if .deadLinks then "not clickable" else "" end) | \(if .safe then "\(.safe.top | pct), \(.safe.bottom | pct), \(.safe.left | pct), \(.safe.right | pct)" else "" end) |"),
    "",
    (.[] | select(.notes) | "- \(.name): \(.notes | join(" "))")'
  rm -rf "$p"
}

gen_feed() {
  # protocol.ts at the recorded commit (it imports nothing), evaluated from a scratch copy
  local p; p=$(mktemp -d "${TMPDIR:-/tmp}/skills-feed.XXXXXX")
  app_show src/acp/protocol.ts > "$p/protocol.ts"
  bun -e '
    const { FEED_TOOLS } = await import(process.argv[1] + "/protocol.ts")
    console.log(JSON.stringify(Object.entries(FEED_TOOLS).map(([name, t]) => ({ name, ...t }))))
  ' "$p" | jq -r --arg head "$HEAD_LINE" '
    $head, "",
    "# The feed'"'"'s tools",
    "",
    "The tools the raea app offers every agent it launches, as the MCP server `feed` (apps/app host/acp/feed-mcp.ts).",
    "PAGE: the feed'"'"'s page answers it, so the app must be open (or a windowless page); PERSON: a click finishes it.",
    "With no page, use the CLI instead: `raea context .` for the brief and the taste, `raea check` for the rules.",
    "",
    (.[] |
      "## \(.name)", "",
      "Access: \(.access // "not tagged").", "",
      .description, "",
      (if ((.inputSchema.properties // {}) | length) > 0 then
        ("| input | | |", "|---|---|---|",
         ((.inputSchema.required // []) as $req | .inputSchema.properties | to_entries[] | .key as $k |
           "| `\(.key)` | \(if ($req | index($k)) then "required" else "optional" end) | \((.value.description // .value.type // "") | gsub("\\|"; "\\\\|")) |"),
         "")
       else ("No input.", "") end))'
  rm -rf "$p"
}

gen_app() {
  # the raea app's window serves MCP (engine/page/host src/mcp.rs): its tools, read from the source as they're declared
  printf '%s\n\n' "$HEAD_LINE"
  cat <<'MD'
# The app's window over MCP

The raea app's window (raea-page-host, `raea-window` inside raea.app) can serve an MCP server on
`http://127.0.0.1:PORT/mcp`: Streamable HTTP, JSON answers. It is how an agent drives the app as a person would and sees
what they see: real input events, the interface's elements with their `data-testid`s, the window as a PNG, and any Bevy
Remote Protocol method. Access: HOST. The packaged app serves it only when started with RAEA_PAGE_MCP_PORT set
(tools/raea-app/launch.sh; RAEA_APP_HEADLESS=1 runs it with no window, as its own checks do); a page host started by
hand serves 7477 unless RAEA_PAGE_MCP_PORT says otherwise (0: none). The conformance suite (sdk/ui/conformance) drives
the app through `input` and `ui`.

MD
  perl -0ne 'while (/\{"name": "([a-z_]+)", "description": (?:"((?:[^"\\]|\\.)*)"|format!\("((?:[^"\\]|\\.)*)")/g) { my ($n, $d) = ($1, $2 // $3); $d =~ s/\\"/"/g; $d =~ s/\{\}/page/g; print "## $n\n\n$d\n\n" }' "$ROOT/engine/page/host/src/mcp.rs"
}

gen_files() {
  local tmp; tmp=$(mktemp -d "${TMPDIR:-/tmp}/skills-gen.XXXXXX")
  # a workspace and a project as raea makes them, with no global config of the person's
  (
    export GIT_CONFIG_GLOBAL="$tmp/gitconfig" GIT_AUTHOR_NAME=gen GIT_AUTHOR_EMAIL=gen@raea GIT_COMMITTER_NAME=gen GIT_COMMITTER_EMAIL=gen@raea
    git config --global raea.root "$tmp/Studio"
    mkdir -p "$tmp/Studio" && cd "$tmp/Studio"
    "$R" workspace init Example >/dev/null
    cd example && "$R" project new Launch >/dev/null
  )
  {
    echo "$HEAD_LINE"
    echo
    echo "# Files"
    echo
    echo "## A workspace and its project"
    echo
    echo "What \`raea workspace init Example\` and then \`raea project new Launch\` make, under raea.root (\`git config"
    echo "--global raea.root\`; unset, ~/Studio where workspaces already are, else ~/Documents/raea, or ~/raea when iCloud"
    echo "keeps Documents). The workspace is one git repo; media/ and out/ go to LFS."
    echo
    echo '```'
    (cd "$tmp/Studio" && find example -path '*/.git' -prune -o -print | grep -v '/\.git$' | LC_ALL=C sort | sed 's|[^/]*/|  |g')
    echo '```'
    echo
    echo "## ~/.raea"
    echo
    echo "The files and folders under ~/.raea that raea's CLI, its engine and the raea app keep, the environment variable"
    echo "that moves each (when there is one) and the files that name them."
    echo
    echo "| path | moved by | named in |"
    echo "|---|---|---|"
    { git grep -nE '\.raea(/|", ")[A-Za-z]' -- engine io runtime ':!*.test.*' ':!*/tests/*' ':!*.md'
      app_grep -nE '\.raea(/|", ")[A-Za-z]' -- host ':!*.test.*' | sed "s|^|apps/app/|"
    } 2>/dev/null | perl -ne '
        my ($f, $text) = /^([^:]+):\d+:(.*)$/ or next;
        while ($text =~ m{(?<![\w.-]/)(?<![\w-])\.raea(?:/|", ")([A-Za-z][A-Za-z0-9_.-]*(?:/[A-Za-z][A-Za-z0-9_.-]*)?)}g) {
          my $p = $1; $p =~ s/\.$//; next if $p =~ /^(workspace|project)\b/;
          # the variable that moves it: process.env.X ??, env::var("X"), or raea_io_home::env_path("X", ".raea/...")
          my $env = $text =~ /(?:process\.env\.(RAEA_\w+)\s*\?\?|env::var(?:_os)?\("(RAEA_\w+)"\)|env_path\("(RAEA_\w+)",)/ ? ($1 // $2 // $3) : "";
          $env{$p} ||= $env; $files{$p}{$f} = 1;
        }
        END { for my $p (sort keys %files) { printf "| `~/.raea/%s` | %s | %s |\n", $p, $env{$p} ? "`$env{$p}`" : "", join(", ", sort keys %{$files{$p}}) } }'
    echo
    echo "## The spec files"
    echo
    echo "Each spec's fields, as raea/brief's types (sdk/raea/src/brief.gen.ts, generated from the schemas in core/brief that"
    echo "\`raea spec\` checks against): brief.ts is a Brief, NAME.script.ts a Script, taste.ts a Taste and NAME.parts.ts an object's Parts."
    echo "A field marked ? may be left out."
    echo
    echo '```ts'
    grep -v '^// Generated' "$ROOT/sdk/raea/src/brief.gen.ts" | sed '/^$/d'
    echo '```'
  }
  rm -rf "$tmp"
}

gen_sdk() {
  bun -e '
    const root = process.argv[1], dir = root + "/sdk/raea/src", fs = require("fs"), path = require("path")
    const tx = { ts: new Bun.Transpiler({ loader: "ts" }), tsx: new Bun.Transpiler({ loader: "tsx" }) }
    // an entry that is `export * from "@raea/<package>"` (raea/editor, most of raea/audio) gives the names of the
    // module it points at, found through the SDK'"'"'s own path map (sdk/tsconfig.base.json), and of what that re-exports
    const paths = require(root + "/sdk/tsconfig.base.json").compilerOptions.paths
    const find = (spec, from) => {
      const at = spec.startsWith(".") ? [path.resolve(path.dirname(from), spec)] : Object.entries(paths).flatMap(([k, v]) =>
        k === spec ? v.map((p) => path.resolve(root, "sdk", p)) : k.endsWith("/*") && spec.startsWith(k.slice(0, -1)) ? v.map((p) => path.resolve(root, "sdk", p.replace("*", spec.slice(k.length - 1)))) : [])
      for (const c of at) for (const e of ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]) if (fs.existsSync(c + e) && fs.statSync(c + e).isFile()) return c + e
      console.error(`FAIL skills: ${path.relative(root, from)}:1: export * from "${spec}" leads to no file; fix: name it in sdk/tsconfig.base.json paths`)
      process.exit(1)
    }
    const names = (file, seen) => {
      if (seen.has(file)) return []
      seen.add(file)
      const src = fs.readFileSync(file, "utf8")
      const own = tx[file.endsWith(".tsx") ? "tsx" : "ts"].scan(src).exports.filter((n) => n !== "default")
      return [...own, ...[...src.matchAll(/^export \* from ["'"'"']([^"'"'"']+)["'"'"']/gm)].flatMap((m) => names(find(m[1], file), seen))]
    }
    const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts|^page-layout\.ts|^dom-[a-z-]+\.ts)$/
    const files = [...new Bun.Glob("*.{ts,tsx}").scanSync(dir)].filter((f) => !skip.test(f)).sort()
    const rows = files.map((f) => ({ entry: f.startsWith("index.") ? "raea" : "raea/" + f.replace(/\.tsx?$/, ""), file: "sdk/raea/src/" + f, names: [...new Set(names(dir + "/" + f, new Set()))].sort() }))
    console.log(JSON.stringify(rows.sort((a, b) => (a.entry === "raea" ? -1 : b.entry === "raea" ? 1 : a.entry.localeCompare(b.entry)))))
  ' "$ROOT" | jq -r --arg head "$HEAD_LINE" '
    $head, "",
    "# The raea SDK",
    "",
    "What each import gives a composition, a game or a spec (values only; their types come along). Components start",
    "with a capital, hooks with `use`. A component'"'"'s props are in its file.",
    "",
    (.[] | select((.names | length) > 0) |
      "## `\(.entry)` (\(.file))", "",
      ([.names[] | "`\(.)`"] | join(", ")), "")'
}


# the hand-written text the gate reads: the skills (not their generated references) and the craft guides
texts() { { git ls-files -co --exclude-standard -- sdk/guides/craft; [ -d "$SK" ] && find "$SK/raea" -type f; } | grep -E '\.md$' | grep -v '/reference/'; }

# the raea is older than the help's sources as committed: its help would be stale (L0's cli surface step rebuilds it)
help_stale() {
  [ "${SKILLS_STRICT:-0}" = 1 ] && return 1
  local built newest
  built=$(stat -f %m "$R" 2>/dev/null || stat -c %Y "$R")
  # the history is the binary's own checkout's (an L0 export has none)
  local co; co=$(cd "$(dirname "$(realpath "$R")")/../.." 2>/dev/null && pwd); [ -f "$co/engine/cli/src/cli.rs" ] || co=$ROOT
  newest=$(git -C "$co" log -1 --no-merges --format=%at -- engine/cli/src apps/check/src apps/game/src apps/tools/src apps/engines/src runtime/react/src/scene.rs runtime/react/src/scene 2>/dev/null)
  [ -n "$newest" ] && [ "$built" -lt "$newest" ]
}

# Surface coverage (raea-skills docs/TREE.md): each verb in raea's help, each SDK entry (sdk/raea/src) and each feed tool,
# with whether a guide or the skill teaches it outside the generated reference (texts(): sdk/guides/craft and the skill's
# own files, not reference/). A row is KIND<TAB>NAME<TAB>taught|untaught|skip. The reference lists everything; coverage
# asks whether anything says when and how to use it. COVERAGE_SKIP names what an agent never runs, each with why.
COVERAGE_SKIP="verb:hook (raea skills install sets it up; an agent never runs it)
verb:traces (raea's own session logs, for whoever debugs raea)
verb:voice (raea.app's Ideate runs it and talks to it in lines of JSON; an agent never does)
verb:bake (until BK5: today only --compare, raea's own measure of its bake against Cycles; BK5 teaches <LightBake> and raea bake light in bevy/lights, docs/bake.feature)
module:dev_tools (raea's own debugging overlays)
module:test (raea's test harness, for raea's own tests)
module:page-layout (installed by the entry: a composition reads its layout through the DOM on its refs, docs/layout-reads.feature)
module:dom-reads (installed by the entry on every ref; what it adds is the web's own API)
module:dom-tree (installed by the entry on every ref; what it adds is the web's own API)
module:random-colors (its names, random, interpolateColors and OffthreadVideo, come from raea itself; craft/motion.md teaches them)"
coverage() {
  local corpus v m t f; corpus=$(mktemp "${TMPDIR:-/tmp}/skills-cov.XXXXXX")
  texts | while read -r f; do cat "$f"; echo; done > "$corpus"
  row() {  # KIND NAME PATTERN (an extended regex)
    if printf '%s\n' "$COVERAGE_SKIP" | grep -q "^$1:$2 "; then printf '%s\t%s\tskip\n' "$1" "$2"
    elif grep -qE "$3" "$corpus"; then printf '%s\t%s\ttaught\n' "$1" "$2"
    else printf '%s\t%s\tuntaught\n' "$1" "$2"; fi
  }
  if [ "${stale_help:-0}" != 1 ]; then
    for v in $("$R" help --json | jq -r '.verbs[].verb' | sort -u); do row verb "$v" "raea $v([^a-z_-]|\$)"; done
  fi
  for f in sdk/raea/src/*.ts sdk/raea/src/*.tsx; do
    m=${f##*/}; m=${m%.tsx}; m=${m%.ts}
    case $m in index | prelude | pure | native-calls | *.gen) continue ;; esac
    row module "$m" "raea/$m([^a-z_-]|\$)"
  done
  for t in $(gen_feed | sed -n 's/^## //p'); do row tool "$t" "(^|[^a-z_])$t([^a-z_]|\$)"; done
  rm -f "$corpus"
}

check() {
  local fail=0 tmp; tmp=$(mktemp -d "${TMPDIR:-/tmp}/skills-check.XXXXXX")
  [ -f "$SK/raea/SKILL.md" ] || { echo "FAIL skills: $SK/raea/SKILL.md:1: missing; fix: git submodule update --init skills (raea-skills, at the commit raea pins)"; rm -rf "$tmp"; return 1; }
  # 1. stale references: what gen writes now, against what's committed beside the skill
  if help_stale; then
    echo "skills: note $R is older than the help's sources; cli.md and the flags aren't checked (rebuild raea-cli)"
  fi
  local stale_help=0; help_stale && stale_help=1
  SKILLS_OUT=$tmp/ref SKILLS_COPY_OUT=$tmp/copies R=$R SKIP_CLI=$stale_help "$0" gen-into >/dev/null || { echo "FAIL skills: tools/skills.sh gen failed"; rm -rf "$tmp"; return 1; }
  for f in cli feed files sdk app platforms; do
    [ "$f" = cli ] && [ $stale_help = 1 ] && continue
    if ! diff -q "$tmp/ref/$f.md" "$SK/raea/reference/$f.md" >/dev/null 2>&1; then
      # the shared GitButler tree holds every applied lane's code, so what gen writes there isn't what main + one lane
      # gives: a note here, a failure in L1's export (origin/main + the lane)
      if [ "${SKILLS_STRICT:-0}" = 1 ]; then
        echo "FAIL skills: $SK/raea/reference/$f.md:1: differs from what this release generates; fix: tools/skills.sh gen with this raea, and commit it"
        fail=1
      elif [ "$(git symbolic-ref -q HEAD 2>/dev/null)" = refs/heads/gitbutler/workspace ]; then
        echo "skills: warning $SK/raea/reference/$f.md differs from what this tree generates (other lanes' code is applied here; L1's export decides)"
      elif [ "$f" = cli ] && [ "$(cd "$(dirname "$(realpath "$R")")/../.." && pwd)" != "$ROOT" ]; then
        # the help is the binary's, built from another tree (L1's export runs the shared raea, which holds every
        # applied lane): a note here; a clean checkout with its own build (release.sh) fails on it
        echo "skills: warning $SK/raea/reference/cli.md differs from the help of $R, built from another tree"
      else
        echo "FAIL skills: $SK/raea/reference/$f.md:1: stale; fix: tools/skills.sh gen on origin/main + this lane (the shared tree holds other lanes too), and commit it"
        fail=1
      fi
    fi
  done
  # the guides the skill carries (copies()): each a copy of its source, and no copy left whose guide is gone, so raea-skills
  # reads whole on its own (and on GitHub) and says what `raea guide` says
  local g c d
  while IFS=$'\t' read -r g c; do
    cmp -s "$g" "$SK/raea/$c" && continue
    if [ "$(git symbolic-ref -q HEAD 2>/dev/null)" = refs/heads/gitbutler/workspace ]; then
      echo "skills: warning $SK/raea/$c differs from $g (other lanes' code is applied here; L1's export decides)"
    else
      echo "FAIL skills: $SK/raea/$c:1: isn't a copy of $g; fix: tools/skills.sh gen, and commit it in raea-skills, then the pointer"; fail=1
    fi
  done < <(copies)
  for d in $COPY_DIRS; do
    for c in "$SK/raea/$d"/*; do
      [ -f "$c" ] || continue
      c=${c#"$SK/raea/"}
      case " $SKILL_ONLY " in *" $c "*) continue ;; esac
      copies | cut -f2 | grep -qxF "$c" || { echo "FAIL skills: $SK/raea/$c:1: copies a guide that's gone; fix: delete it in raea-skills, or name the guide that replaced it"; fail=1; }
    done
  done
  # surface coverage: a warning per verb, SDK entry or feed tool nothing teaches yet (tools/skills.sh coverage lists all)
  coverage | awk -F'\t' -v sk="$SK/raea" '$3 == "untaught" { k = $1 == "verb" ? "raea " $2 : $1 == "module" ? "raea/" $2 : "the feed tool " $2; print "skills: coverage: " k " is in raea, but no guide or router says when to use it; fix: teach it in the router for its domain (" sk "/DOMAIN.md) or its guide (sdk/guides/craft), or add it to COVERAGE_SKIP with why" }'
  # 2. retired words (docs/skills.glossary.md), whole words where they start with a letter
  local words g=${RAEA_GLOSSARY:-docs/skills.glossary.md}  # the glossary is the maintainers' (private); without it, no retired words
  words=$( [ -f "$g" ] && sed -n '/<!-- retired -->/,/<!-- \/retired -->/p' "$g" | sed '1d;$d' || true )
  # 3. flags: each `raea VERB ... --flag` in a code span or block, against the verb's flags in raea help --json
  touch "$tmp/flags"
  [ $stale_help = 1 ] || "$R" help --json | jq -r '.verbs[] | select(.own_parser | not) | "\(.verb)\t\([.flags[].flag] | join(" "))"' > "$tmp/flags"
  # 4. RAEA_* variables: read somewhere outside the docs
  git grep -ohE 'RAEA_[A-Z0-9_]+' -- ':!*.md' ':!*.feature' > "$tmp/vars" 2>/dev/null || true
  app_grep -ohE 'RAEA_[A-Z0-9_]+' -- ':!*.md' >> "$tmp/vars" 2>/dev/null || true
  sort -u -o "$tmp/vars" "$tmp/vars"
  texts | WORDS="$words" FLAGS="$tmp/flags" VARS="$tmp/vars" STALE_HELP=$stale_help perl -e '
    my @words = grep { length } split /\n/, $ENV{WORDS};
    my %flags; open my $fh, "<", $ENV{FLAGS}; while (<$fh>) { chomp; my ($v, $f) = split /\t/, $_, 2; $flags{$v} = { map { $_ => 1 } split / /, ($f // "") } }
    my %vars; open my $vh, "<", $ENV{VARS}; while (<$vh>) { chomp; $vars{$_} = 1 }
    my $fail = 0;
    sub bad { my ($f, $n, $what, $fix) = @_; print "FAIL skills: $f:$n: $what; fix: $fix\n"; $fail = 1 }
    while (my $f = <STDIN>) {
      chomp $f; open my $in, "<", $f or next; my ($n, $block) = (0, 0); (my $dir = $f) =~ s{/[^/]*$}{};
      while (my $l = <$in>) {
        $n++;
        $block = !$block if $l =~ /^\s*```/;
        for my $w (@words) {
          my $re = $w =~ /^\w/ ? qr/\b\Q$w\E\b/i : $w =~ /^\./ ? qr/\Q$w\E\b/ : qr/(?<![\w-])\Q$w\E\b/;
          bad($f, $n, "retired word \"$w\"", "say it as docs/skills.glossary.md does") if $l =~ $re;
        }
        # the code on the line: all of it in a block, else its `spans`
        my @code = $block ? ($l) : ($l =~ /`([^`]+)`/g);
        if (!$ENV{STALE_HELP}) {
          for my $c (@code) {
            while ($c =~ /\braea ([a-z][a-z-]*)((?:\s+[^\s|;#]+)*)/g) {
              my ($v, $rest) = ($1, $2); next unless $flags{$v};
              for my $fl ($rest =~ /(?<![\w-])(--[a-z][\w-]*)/g) {
                bad($f, $n, "raea $v takes no $fl", "raea help --json lists its flags (reference/cli.md)") unless $flags{$v}{$fl};
              }
            }
          }
        }
        for my $v ($l =~ /\b(RAEA_[A-Z0-9_]+)/g) { bad($f, $n, "$v is read nowhere", "drop it, or name the variable that replaced it") unless $vars{$v} }
        while ($l =~ /\]\(([^)#\s]+)(?:#[^)]*)?\)/g) {
          my $t = $1; next if $t =~ m{^(https?:|mailto:|/)};
          bad($f, $n, "link to $t goes nowhere", "point it at a file that exists") unless -e "$dir/$t";
        }
      }
    }
    exit $fail;' || fail=1
  rm -rf "$tmp"
  # 5. a section's sources exist
  local f a b head src x
  while IFS=$'\t' read -r f a b head src; do
    for x in $src; do [ -e "$x" ] || { [ -n "${RAEA_LIVE:-}" ] && [ -e "$RAEA_LIVE/$x" ]; } || { echo "FAIL skills: $f:$a: \"$head\" names source $x, which doesn't exist; fix: name the file that replaced it"; fail=1; }; done
  done < <(sections)
  cochange
  [ $fail -eq 0 ] && echo "skills: ok"
  return $fail
}

# each hand-written section that names its sources: file, its first and last line, heading, sources
sections() {
  texts | while IFS= read -r f; do
    awk -v f="$f" '
      function flush() { if (head != "" && src != "") printf "%s\t%d\t%d\t%s\t%s\n", f, start, NR - 1, head, src }
      /^## / { flush(); head = substr($0, 4); start = NR; src = "" }
      /^<!-- sources: / { s = $0; sub(/^<!-- sources: /, "", s); sub(/ *-->.*$/, "", s); src = s }
      END { NR++; flush() }' "$f"
  done
}

# a change to a section's sources that leaves the section alone (SK4): a warning, answered in the landing message
cochange() {
  local changed
  if [ -n "${SKILLS_CHANGED:-}" ]; then changed=$SKILLS_CHANGED
  else changed=$(git diff --name-only "$(git merge-base HEAD origin/main 2>/dev/null || echo HEAD)" 2>/dev/null; git diff --name-only HEAD 2>/dev/null); fi
  [ -n "$changed" ] || return 0
  sections | while IFS=$'\t' read -r f a b head src; do
    local hit="" s
    for s in $src; do grep -qE "^${s//./\\.}(/|$)" <<< "$changed" && hit="$hit $s"; done
    [ -n "$hit" ] || continue
    # the section counts as touched when its file changed within its lines (or, with no history here, at all)
    # (a skill in raea-skills counts as touched when the pointer moved: raea's history doesn't see inside it)
    case $f in "$SK"/*) grep -qx skills <<< "$changed" && continue ;; esac
    if grep -qx "$f" <<< "$changed"; then
      [ -n "${SKILLS_CHANGED:-}" ] && continue
      git diff -U0 "$(git merge-base HEAD origin/main 2>/dev/null || echo HEAD)" -- "$f" | grep -E '^@@' | sed -E 's/^@@ [^+]*\+([0-9]+)(,([0-9]+))?.*/\1 \3/' |
        awk -v a="$a" -v b="$b" '{ n = ($2 == "" ? 1 : $2); if ($1 <= b && $1 + n - 1 >= a) t = 1 } END { exit !t }' && continue
    fi
    echo "skills: warning $f:$a: \"$head\" names$hit, which changed while it didn't; say in the landing message whether it still holds (\"checked, still true\") or edit it"
  done
}

# every section with sources, by how many commits to them it has missed since its own lines last changed
stale() {
  sections | while IFS=$'\t' read -r f a b head src; do
    local t n bl
    case $f in "$SK"/*) bl=(git -C skills blame -L "$a,$b" --porcelain -- "${f#skills/}") ;; *) bl=(git blame -L "$a,$b" --porcelain -- "$f") ;; esac
    t=$("${bl[@]}" 2>/dev/null | awk '/^committer-time / { if ($2 > m) m = $2 } END { print m + 0 }')
    [ "$t" -gt 0 ] || t=$(date +%s)
    # shellcheck disable=SC2086
    n=$(git rev-list --count --since="$t" HEAD -- $src 2>/dev/null || echo 0)
    printf '%s\t%s:%s\t%s\n' "$n" "$f" "$a" "$head"
  done | sort -rn -k1,1 | awk -F'\t' 'BEGIN { print "missed  section" } { printf "%6d  %s  %s\n", $1, $2, $3 }'
}

case "${1:-}" in
  gen | gen-into)
    R=${R:-$(raea_bin)}
    [ -x "$R" ] || { echo "skills.sh: no raea to read the help from (RAEA_BIN, or build raea-cli)" >&2; exit 2; }
    mkdir -p "$OUT"
    [ "${SKIP_CLI:-0}" = 1 ] || gen_cli > "$OUT/cli.md"
    gen_feed > "$OUT/feed.md"
    gen_files > "$OUT/files.md"
    gen_sdk > "$OUT/sdk.md"
    gen_app > "$OUT/app.md"
    gen_platforms > "$OUT/platforms.md"
    copies | while IFS=$'\t' read -r g c; do mkdir -p "$COPY_OUT/$(dirname "$c")" && cp "$g" "$COPY_OUT/$c"; done
    if [ "$1" = gen ]; then wc -l "$OUT"/*.md; fi
    ;;
  check)
    R=$(raea_bin)
    [ -x "$R" ] || { echo "FAIL skills: no raea to read the help from (RAEA_BIN, or build raea-cli)"; exit 1; }
    check
    ;;
  coverage)
    R=$(raea_bin)
    [ -x "$R" ] || { echo "skills.sh: no raea to read the help from (RAEA_BIN, or build raea-cli)" >&2; exit 2; }
    coverage | awk -F'\t' '{ n[$1]++; if ($3 == "untaught") { u[$1]++; l[$1] = l[$1] " " $2 } } END { for (k in n) printf "%-7s %3d of %3d taught%s\n", k, n[k] - u[k], n[k], u[k] ? ";  untaught:" l[k] : "" }' | sort
    ;;
  check-cli)
    R=$(raea_bin)
    [ -x "$R" ] || { echo "FAIL skills: no raea to read the help from (RAEA_BIN, or build raea-cli)"; exit 1; }
    d=$(mktemp)
    # a Windows checkout has CRLF line ends (Git's autocrlf) and the help's are LF: only the text is compared
    if ! diff -u --strip-trailing-cr $SK/raea/reference/cli.md <(gen_cli) > "$d"; then
      echo "FAIL skills: $SK/raea/reference/cli.md:1: differs from the help of $R; fix: tools/skills.sh gen with a raea built from this tree, and commit it"
      head -40 "$d"; rm -f "$d"; exit 1
    fi
    rm -f "$d"
    echo "skills: cli.md matches the help of $R"
    ;;
  stale) stale ;;
  *) echo "usage: tools/skills.sh gen | check | check-cli | stale" >&2; exit 2 ;;
esac