Files
holocron/plugins/kyberforge/.apm/skills/skill-author/scripts/new-skill.sh
Defame1297 36723ae3fc fix(skill-author): fail loudly when scaffold repair cannot substitute
Why: repair_placeholders ran inside a command substitution, so a failing
sed left an emptied file behind and the script still exited 0 reporting
success.

- write via tmp file and abort on sed or mv failure
- re-check the target before moving staging into place
- stage in a dot-prefixed mktemp dir so a killed run leaves no fake skill
- source apm claims in deployment-modes.md; tag untyped code blocks

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KkT7RSDwDbmrM9T34b6sTi
2026-09-29 08:00:22 +00:00

270 lines
10 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$SKILL_DIR/../assets/templates"
usage() {
cat <<EOF
Usage: new-skill.sh <skill-name> <path>
Create a new skill scaffold by copying annotated templates to the resolved
destination. <path> is any existing path inside or at the target — a
package or a standalone location. It does not have to be a package root
itself.
The script walks up from <path> to pick one of two modes:
Package mode:
If an apm.yml with a top-level 'type:' field (instructions, skill,
hybrid, or prompts) is found at or above <path>, the skill is
scaffolded into <package-root>/.apm/skills/<skill-name>/ — not under
<path> itself. An apm.yml with no 'type:' field is a marketplace-only
manifest, not a package; it is skipped and the walk continues upward.
Standalone mode:
If the walk reaches a '.git' directory or the filesystem root without
finding a type-bearing apm.yml, the skill is scaffolded directly into
<path>/<skill-name>/, exactly as <path> was given.
Arguments:
skill-name Kebab-case skill identifier (e.g. my-tool, data-analyzer).
Must match the directory name exactly.
path Any existing path inside/at the target. Used to locate the
package (package mode) or as the literal parent directory
(standalone mode). Must already exist.
Examples: ~/.agents/skills/ packages/my-pkg/some/subdir/
Output:
Package mode: <package-root>/.apm/skills/<skill-name>/
Standalone mode: <path>/<skill-name>/
Exit codes:
0 Scaffold created, destination already complete (no-op), or a partial
scaffold from an earlier failed run repaired
1 Invalid arguments, missing path, templates not found, name
substitution failed, or the destination appeared mid-build
EOF
}
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage
exit 0
fi
if [[ $# -lt 2 ]]; then
echo "Error: skill-name and path are required." >&2
echo "" >&2
usage >&2
exit 1
fi
SKILL_NAME="$1"
TARGET_INPUT="$2"
# Validate skill name format
if ! grep -qE '^[a-z0-9]+(-[a-z0-9]+)*$' <<< "$SKILL_NAME"; then
echo "Error: skill-name must use lowercase letters, numbers, and hyphens only." >&2
echo " No leading, trailing, or consecutive hyphens." >&2
echo " Received: '$SKILL_NAME'" >&2
exit 1
fi
# Validate templates directory exists
if [[ ! -d "$TEMPLATES_DIR" ]]; then
echo "Error: templates directory not found at '$TEMPLATES_DIR'." >&2
echo " Run this script from its original location inside the skill-author skill." >&2
exit 1
fi
# Validate path exists
if [[ ! -d "$TARGET_INPUT" ]]; then
echo "Error: path '$TARGET_INPUT' does not exist." >&2
exit 1
fi
# True if apm_yml's top-level `type:` line names one of the four APM package
# types (instructions/skill/hybrid/prompts) — mirrors validate.sh's
# APM_TYPE_RE: an optional quote around the value must be closed by the
# *same* quote character (a mismatched or unterminated quote is rejected,
# not silently stripped), and the value must be followed by whitespace or
# end-of-line so `prompts-only` doesn't false-match on the `prompts` prefix.
# `|| [[ -n "$line" ]]` in the read condition also processes a final line
# that lacks a trailing newline, which `read` alone would otherwise skip.
# Identical to agent-author's new-agent.sh copy of this helper.
is_apm_package_manifest() {
local apm_yml="$1" line
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$line" =~ ^type:[[:space:]]*(instructions|skill|hybrid|prompts)([[:space:]]|$) ]]; then
return 0
fi
if [[ "$line" =~ ^type:[[:space:]]*([\"\'])(instructions|skill|hybrid|prompts)([\"\'])([[:space:]]|$) ]] \
&& [[ "${BASH_REMATCH[1]}" == "${BASH_REMATCH[3]}" ]]; then
return 0
fi
done < "$apm_yml"
return 1
}
# ---------------------------------------------------------------------------
# Walk up from <path> looking for a type-bearing apm.yml (package mode) or a
# .git boundary / filesystem root (standalone mode). An apm.yml with no
# top-level 'type:' field is a marketplace-only manifest — skip it and keep
# walking up. Prints one space-separated line: mode, then the resolved root.
# ---------------------------------------------------------------------------
find_package_root() {
local current
current="$(cd "$1" && pwd)"
while true; do
if [[ -f "$current/apm.yml" ]]; then
if is_apm_package_manifest "$current/apm.yml"; then
echo "package $current"
return 0
fi
# apm.yml exists but has no type: field — marketplace-only manifest.
# Not a package match; keep walking up.
fi
# .git is a directory in a normal checkout but a file (`gitdir: ...`) in
# a git worktree — -e covers both.
if [[ -e "$current/.git" ]]; then
echo "no-package $current"
return 0
fi
local parent
parent="$(dirname "$current")"
if [[ "$parent" == "$current" ]]; then
echo "no-package $current"
return 0
fi
current="$parent"
done
}
# `mapfile`/`readarray` are bash 4.0+ builtins with no fallback on macOS's
# stock /bin/bash 3.2 — read the single space-separated output line with a
# plain `read` instead (bash 3.2-safe). `read` consumes only one line, so
# mode and path must be on the same line: MODE first (never contains
# whitespace), PKG_ROOT last (safely absorbs a path containing spaces).
WALK_OUTPUT="$(find_package_root "$TARGET_INPUT")"
read -r MODE PKG_ROOT <<< "$WALK_OUTPUT"
if [[ "$MODE" == "package" ]]; then
TARGET="$PKG_ROOT/.apm/skills/$SKILL_NAME"
else
TARGET="$TARGET_INPUT/$SKILL_NAME"
fi
# Files carrying the SKILL_NAME placeholder token, each paired with the exact
# template line that marks it as still unsubstituted. Only that whole line
# counts: a finished skill may legitimately mention SKILL_NAME in its prose.
SUBST_FILES=("SKILL.md" "tests/README.md")
SUBST_MARKERS=("name: SKILL_NAME" "bats <destination-dir>/SKILL_NAME/tests/")
# Replace SKILL_NAME in one file. `sed -i` is not portable — GNU takes an
# optional attached suffix, BSD/macOS requires a separate suffix argument and
# reads the expression as one — so write to a temp file and move it over.
# The move runs only if sed succeeded: a failed sed leaves an empty or partial
# temp file, and moving that over the original would destroy it.
substitute_file() {
local f="$1"
if sed "s/SKILL_NAME/$SKILL_NAME/g" "$f" > "$f.tmp" && mv "$f.tmp" "$f"; then
return 0
fi
rm -f "$f.tmp"
echo "Error: could not substitute the skill name in '$f'." >&2
return 1
}
# Substitute every placeholder file under dir $1 (a fresh template copy).
substitute_name() {
local dir="$1" rel
for rel in "${SUBST_FILES[@]}"; do
if [[ -f "$dir/$rel" ]]; then
substitute_file "$dir/$rel" || return 1
fi
done
return 0
}
# Substitute only the placeholder files under dir $1 that still carry their
# template marker line. Sets REPAIRED to how many were repaired; returns 1 on
# the first failure. Called directly, never inside $(...): a command
# substitution would swallow the failure and let the caller report success.
REPAIRED=0
repair_placeholders() {
local dir="$1" i f
REPAIRED=0
for i in "${!SUBST_FILES[@]}"; do
f="$dir/${SUBST_FILES[$i]}"
if [[ -f "$f" ]] && grep -qxF "${SUBST_MARKERS[$i]}" "$f"; then
substitute_file "$f" || return 1
REPAIRED=$((REPAIRED + 1))
fi
done
return 0
}
if [[ -d "$TARGET" ]]; then
# A scaffold left half-built by an earlier failed run still carries a
# template marker line; finish it instead of reporting a silent no-op.
# Anything else — including a complete skill — is left untouched.
if ! repair_placeholders "$TARGET"; then
echo "Error: repair of '$TARGET' failed; no file was left half-written." >&2
exit 1
fi
if [[ "$REPAIRED" -gt 0 ]]; then
# The marker line proves only that the name was never substituted, not
# that the earlier copy finished — a file may still be missing.
echo "Repaired partial scaffold at '$TARGET' — only the name placeholder (SKILL_NAME) was substituted." >&2
echo "The earlier run may also have left files missing: run /factory-audit on it, or delete it and re-run this script." >&2
exit 0
fi
echo "Scaffold already exists at '$TARGET' — nothing to do." >&2
exit 0
fi
mkdir -p "$(dirname "$TARGET")"
# Build in a sibling staging directory and rename it into place only once
# complete, so a failure mid-build never leaves a half-built $TARGET behind.
# The dot prefix matters: a SIGKILL skips the trap, and a leftover must not
# look like a skill to anything scanning .apm/skills/.
STAGING="$(mktemp -d "$(dirname "$TARGET")/.new-skill.XXXXXX")"
trap 'rm -rf "$STAGING"' EXIT
# mktemp creates the directory 0700; give the skill the umask default instead.
chmod "$(umask -S)" "$STAGING"
cp -R "$TEMPLATES_DIR/." "$STAGING"
substitute_name "$STAGING"
# $TARGET may have appeared since the check above (a concurrent run). `mv`
# onto an existing directory nests the source inside it instead of failing,
# and GNU `mv -T` is not portable, so re-check immediately before the rename.
# This narrows the window to the gap between two syscalls; it does not close it.
if [[ -e "$TARGET" ]]; then
echo "Error: '$TARGET' appeared while the scaffold was being built; left it untouched." >&2
exit 1
fi
mv "$STAGING" "$TARGET"
trap - EXIT
if [[ "$MODE" == "package" ]]; then
echo "Mode: package — type-bearing apm.yml found at '$PKG_ROOT'" >&2
echo "Scaffold created: $TARGET" >&2
echo "" >&2
echo "Note: if '$PKG_ROOT/apm.yml' has an explicit 'includes:' list (not 'auto')," >&2
echo " add '.apm/skills/$SKILL_NAME/' to it." >&2
else
echo "Mode: standalone — no type-bearing apm.yml found above '$TARGET_INPUT'" >&2
echo "Scaffold created: $TARGET" >&2
fi
echo "" >&2
echo "Next steps:" >&2
echo " 1. Fill in $TARGET/SKILL.md — replace all FILL IN: placeholders." >&2
echo " Description: 250 chars target / 400 ceiling. Body: 600 / 900, body only." >&2
echo " 2. Add scripts to scripts/ if needed (or delete the directory)" >&2
echo " 3. Add docs to references/ if needed (or delete the directory)" >&2
echo " 4. Add resources to assets/ if needed (or delete the directory)" >&2
echo " 5. Add tests to tests/ if the skill has scripts (or delete the directory)" >&2
echo " 6. Populate references/sources.md with research sources, or delete it" >&2
echo " 7. Validate: run /factory-audit on $TARGET" >&2