Files
raea/tools/skills.sh
T

345 lines
19 KiB
Bash
Executable File

#!/bin/bash
# The raea skill's generated references (docs/skills.feature SK1-SK2): the hand-written core, sdk/skills/raea/SKILL.md,
# 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 sdk/skills/raea/reference/{cli,feed,files,sdk,app}.md
# 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 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), and
# RAEA_APP the feed app's checkout (default apps/app; an L0 export has no submodules, so L0 names the shared one), read
# at RAEA_APP_REV: the commit raea's tree records for apps/app (L0 passes its tree's), so what's generated follows the
# submodule pointer, not whatever that checkout has on disk.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
OUT=${SKILLS_OUT:-sdk/skills/raea/reference}
HEAD_LINE="<!-- generated by tools/skills.sh gen; do not edit -->"
APP=${RAEA_APP:-apps/app}
[ -f "$APP/src/acp/protocol.ts" ] || { echo "skills.sh: no feed app at $APP (RAEA_APP names its checkout)" >&2; exit 2; }
APP=$(cd "$APP" && pwd)
APP_REV=${RAEA_APP_REV:-$(git rev-parse -q --verify HEAD:apps/app 2>/dev/null || git -C "$APP" rev-parse HEAD)}
git -C "$APP" cat-file -e "$APP_REV" 2>/dev/null || { echo "skills.sh: apps/app has no commit $APP_REV (fetch raea-feed)" >&2; exit 2; }
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_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")
git -C "$APP" show "$APP_REV: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 controller` for the controllers, `raea context .` for the brief.",
"",
(.[] |
"## \(.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\`, else ~/Studio). 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'
git -C "$APP" grep -nE '\.raea(/|", ")[A-Za-z]' "$APP_REV" -- host ':!*.test.*' | sed "s|^$APP_REV:|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/;
my $env = $text =~ /(?:process\.env\.(RAEA_\w+)\s*\?\?|env::var(?:_os)?\("(RAEA_\w+)"\))/ ? ($1 // $2) : "";
$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, plan.ts a Plan and"
echo "controllers/ID.ts a Controller. 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"
const t = new Bun.Transpiler({ loader: "tsx" })
const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.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: t.scan(require("fs").readFileSync(dir + "/" + f, "utf8")).exports.filter((n) => n !== "default").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/skills/raea*' sdk/guides/craft | grep -E '\.md$' | grep -v '/reference/' | grep -v '^sdk/skills/raea-work/'; }
# 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 runtime/react/src/scene.rs runtime/react/src/scene 2>/dev/null)
[ -n "$newest" ] && [ "$built" -lt "$newest" ]
}
check() {
local fail=0 tmp; tmp=$(mktemp -d "${TMPDIR:-/tmp}/skills-check.XXXXXX")
# 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 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; do
[ "$f" = cli ] && [ $stale_help = 1 ] && continue
if ! diff -q "$tmp/ref/$f.md" "sdk/skills/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: sdk/skills/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 sdk/skills/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 sdk/skills/raea/reference/cli.md differs from the help of $R, built from another tree"
else
echo "FAIL skills: sdk/skills/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
# 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
git -C "$APP" grep -ohE 'RAEA_[A-Z0-9_]+' "$APP_REV" -- ':!*.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)
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
t=$(git blame -L "$a,$b" --porcelain -- "$f" 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"
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
;;
stale) stale ;;
*) echo "usage: tools/skills.sh gen | check | stale" >&2; exit 2 ;;
esac